diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/edu/berkeley/cs162/ThreadPool.java b/src/edu/berkeley/cs162/ThreadPool.java index 968cad4..a691c95 100644 --- a/src/edu/berkeley/cs162/ThreadPool.java +++ b/src/edu/berkeley/cs162/ThreadPool.java @@ -1,115 +1,115 @@ /** * A simple thread pool implementation * * @author Mosharaf Chowdhury (http://www.mosharaf.com) * @author Prashanth Mohan (http://www.cs.berkeley.edu/~prmohan) * * Copyright (c) 2012, University of California at Berkeley * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.berkeley.cs162; import java.util.LinkedList; public class ThreadPool { /** * Set of threads in the threadpool */ protected WorkerThread threads[] = null; protected LinkedList<Runnable> jobs = new LinkedList<Runnable>(); // private Lock jLock; /** * Initialize the number of threads required in the threadpool. * * @param size How many threads in the thread pool. */ public ThreadPool(int size) { threads = new WorkerThread[size]; for(int i=0; i<size; i++) { threads[i] = new WorkerThread(this); threads[i].start(); } // jLock = new Lock(); } /** * Add a job to the queue of tasks that has to be executed. As soon as a thread is available, * it will retrieve tasks from this queue and start processing. * @param r job that has to be executed asynchronously * @throws InterruptedException */ - public void addToQueue(Runnable r) throws InterruptedException + public synchronized void addToQueue(Runnable r) throws InterruptedException { try { // jLock.acquire(); this.jobs.add(r); this.notify(); } finally { // jLock.release(); } } /** * Block until a job is available in the queue and retrieve the job * @return A runnable task that has to be executed * @throws InterruptedException */ public synchronized Runnable getJob() throws InterruptedException { Runnable job; while(jobs.size() == 0) { this.wait(); } job = jobs.remove(); return job; } } /** * The worker threads that make up the thread pool. */ class WorkerThread extends Thread { /** * The constructor. * * @param o the thread pool */ private ThreadPool threadPool; WorkerThread(ThreadPool o) { this.threadPool = o; } /** * Scan for and execute tasks. */ public void run() { while(true) { try { threadPool.getJob().run(); } catch(InterruptedException e){} } } }
true
true
public void addToQueue(Runnable r) throws InterruptedException { try { // jLock.acquire(); this.jobs.add(r); this.notify(); } finally { // jLock.release(); } }
public synchronized void addToQueue(Runnable r) throws InterruptedException { try { // jLock.acquire(); this.jobs.add(r); this.notify(); } finally { // jLock.release(); } }
diff --git a/java/amqp-api/src/main/java/org/zenoss/amqp/impl/PublisherImpl.java b/java/amqp-api/src/main/java/org/zenoss/amqp/impl/PublisherImpl.java index df17f63..3544b28 100644 --- a/java/amqp-api/src/main/java/org/zenoss/amqp/impl/PublisherImpl.java +++ b/java/amqp-api/src/main/java/org/zenoss/amqp/impl/PublisherImpl.java @@ -1,95 +1,95 @@ /* * This program is part of Zenoss Core, an open source monitoring platform. * Copyright (C) 2010, Zenoss Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or (at your * option) any later version as published by the Free Software Foundation. * * For complete information please visit: http://www.zenoss.com/oss/ */ package org.zenoss.amqp.impl; import com.rabbitmq.client.AMQP.BasicProperties; import org.zenoss.amqp.*; class PublisherImpl<T> implements Publisher<T> { protected final ChannelImpl channel; protected final Exchange exchange; protected final MessageConverter<T> converter; PublisherImpl(ChannelImpl channel, Exchange exchange) { this(channel, exchange, null); } PublisherImpl(ChannelImpl channel, Exchange exchange, MessageConverter<T> converter) { this.channel = channel; this.exchange = exchange; this.converter = converter; } @Override public void publish(T body, String routingKey) throws AmqpException { publish(body, null, routingKey); } @Override public void publish(T body, MessagePropertiesBuilder propertiesBuilder, String routingKey) throws AmqpException { if (propertiesBuilder == null) { propertiesBuilder = MessagePropertiesBuilder.newBuilder(); } try { final byte[] rawBody; if (converter != null) { rawBody = this.converter.toBytes(body, propertiesBuilder); } else { rawBody = (byte[]) body; } synchronized (this.channel) { this.channel.getWrapped().basicPublish(exchange.getName(), routingKey, convertProperties(propertiesBuilder.build()), rawBody); } } catch (Exception e) { throw new AmqpException(e); } } private BasicProperties convertProperties(MessageProperties properties) { if (properties == null) { return null; } // TODO: Figure out a better way to share this data and not duplicate - BasicProperties props = new BasicProperties(); - props.setAppId(properties.getAppId()); + BasicProperties.Builder props = new BasicProperties.Builder(); + props.appId(properties.getAppId()); // props.setClusterId(?); - props.setContentEncoding(properties.getContentEncoding()); - props.setContentType(properties.getContentType()); - props.setCorrelationId(properties.getCorrelationId()); + props.contentEncoding(properties.getContentEncoding()); + props.contentType(properties.getContentType()); + props.correlationId(properties.getCorrelationId()); if (properties.getDeliveryMode() != null) { - props.setDeliveryMode(properties.getDeliveryMode().getMode()); + props.deliveryMode(properties.getDeliveryMode().getMode()); } - props.setExpiration(properties.getExpiration()); - props.setHeaders(properties.getHeaders()); - props.setMessageId(properties.getMessageId()); - props.setPriority(properties.getPriority()); - props.setReplyTo(properties.getReplyTo()); - props.setTimestamp(properties.getTimestamp()); - props.setType(properties.getType()); - props.setUserId(properties.getUserId()); - return props; + props.expiration(properties.getExpiration()); + props.headers(properties.getHeaders()); + props.messageId(properties.getMessageId()); + props.priority(properties.getPriority()); + props.replyTo(properties.getReplyTo()); + props.timestamp(properties.getTimestamp()); + props.type(properties.getType()); + props.userId(properties.getUserId()); + return props.build(); } @Override public Exchange getExchange() { return this.exchange; } @Override public Channel getChannel() { return this.channel; } }
false
true
private BasicProperties convertProperties(MessageProperties properties) { if (properties == null) { return null; } // TODO: Figure out a better way to share this data and not duplicate BasicProperties props = new BasicProperties(); props.setAppId(properties.getAppId()); // props.setClusterId(?); props.setContentEncoding(properties.getContentEncoding()); props.setContentType(properties.getContentType()); props.setCorrelationId(properties.getCorrelationId()); if (properties.getDeliveryMode() != null) { props.setDeliveryMode(properties.getDeliveryMode().getMode()); } props.setExpiration(properties.getExpiration()); props.setHeaders(properties.getHeaders()); props.setMessageId(properties.getMessageId()); props.setPriority(properties.getPriority()); props.setReplyTo(properties.getReplyTo()); props.setTimestamp(properties.getTimestamp()); props.setType(properties.getType()); props.setUserId(properties.getUserId()); return props; }
private BasicProperties convertProperties(MessageProperties properties) { if (properties == null) { return null; } // TODO: Figure out a better way to share this data and not duplicate BasicProperties.Builder props = new BasicProperties.Builder(); props.appId(properties.getAppId()); // props.setClusterId(?); props.contentEncoding(properties.getContentEncoding()); props.contentType(properties.getContentType()); props.correlationId(properties.getCorrelationId()); if (properties.getDeliveryMode() != null) { props.deliveryMode(properties.getDeliveryMode().getMode()); } props.expiration(properties.getExpiration()); props.headers(properties.getHeaders()); props.messageId(properties.getMessageId()); props.priority(properties.getPriority()); props.replyTo(properties.getReplyTo()); props.timestamp(properties.getTimestamp()); props.type(properties.getType()); props.userId(properties.getUserId()); return props.build(); }
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/repositories/metadata/DefaultNexusRepositoryMetadataHandler.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/repositories/metadata/DefaultNexusRepositoryMetadataHandler.java index 4d06b4f8d..33b1b3f93 100644 --- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/repositories/metadata/DefaultNexusRepositoryMetadataHandler.java +++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/repositories/metadata/DefaultNexusRepositoryMetadataHandler.java @@ -1,61 +1,61 @@ package org.sonatype.nexus.repositories.metadata; import java.io.IOException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.sonatype.nexus.proxy.NoSuchRepositoryException; import org.sonatype.nexus.proxy.registry.RepositoryRegistry; import org.sonatype.nexus.proxy.repository.Repository; import org.sonatype.nexus.repository.metadata.MetadataHandlerException; import org.sonatype.nexus.repository.metadata.RepositoryMetadataHandler; import org.sonatype.nexus.repository.metadata.model.RepositoryMetadata; import org.sonatype.nexus.repository.metadata.restlet.RestletRawTransport; @Component( role = NexusRepositoryMetadataHandler.class ) public class DefaultNexusRepositoryMetadataHandler extends AbstractLogEnabled implements NexusRepositoryMetadataHandler { @Requirement private RepositoryRegistry repositoryRegistry; @Requirement private RepositoryMetadataHandler repositoryMetadataHandler; public RepositoryMetadata readRemoteRepositoryMetadata( String url ) throws MetadataHandlerException, IOException { // TODO: honor global proxy? Current solution will neglect it RestletRawTransport restletRawTransport = new RestletRawTransport( url ); return repositoryMetadataHandler.readRepositoryMetadata( restletRawTransport ); } public RepositoryMetadata readRepositoryMetadata( String repositoryId ) throws NoSuchRepositoryException, MetadataHandlerException, IOException { Repository repository = repositoryRegistry.getRepository( repositoryId ); - NexusRawTransport nrt = new NexusRawTransport( repository, true, false ); + NexusRawTransport nrt = new NexusRawTransport( repository, false, false ); return repositoryMetadataHandler.readRepositoryMetadata( nrt ); } public void writeRepositoryMetadata( String repositoryId, RepositoryMetadata repositoryMetadata ) throws NoSuchRepositoryException, MetadataHandlerException, IOException { Repository repository = repositoryRegistry.getRepository( repositoryId ); NexusRawTransport nrt = new NexusRawTransport( repository, true, false ); repositoryMetadataHandler.writeRepositoryMetadata( repositoryMetadata, nrt ); } }
true
true
public RepositoryMetadata readRepositoryMetadata( String repositoryId ) throws NoSuchRepositoryException, MetadataHandlerException, IOException { Repository repository = repositoryRegistry.getRepository( repositoryId ); NexusRawTransport nrt = new NexusRawTransport( repository, true, false ); return repositoryMetadataHandler.readRepositoryMetadata( nrt ); }
public RepositoryMetadata readRepositoryMetadata( String repositoryId ) throws NoSuchRepositoryException, MetadataHandlerException, IOException { Repository repository = repositoryRegistry.getRepository( repositoryId ); NexusRawTransport nrt = new NexusRawTransport( repository, false, false ); return repositoryMetadataHandler.readRepositoryMetadata( nrt ); }
diff --git a/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java b/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java index 57895a5..2e08417 100644 --- a/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java +++ b/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java @@ -1,68 +1,68 @@ package powercrystals.powerconverters.power.buildcraft; import java.util.Map.Entry; import net.minecraftforge.common.ForgeDirection; import buildcraft.api.power.IPowerProvider; import buildcraft.api.power.IPowerReceptor; import buildcraft.api.power.PowerFramework; import powercrystals.powerconverters.PowerConverterCore; import powercrystals.powerconverters.power.TileEntityEnergyProducer; public class TileEntityBuildCraftProducer extends TileEntityEnergyProducer<IPowerReceptor> implements IPowerReceptor { private IPowerProvider _powerProvider; public TileEntityBuildCraftProducer() { super(PowerConverterCore.powerSystemBuildCraft, 0, IPowerReceptor.class); _powerProvider = PowerFramework.currentFramework.createPowerProvider(); _powerProvider.configure(0, 0, 0, 0, 0); } @Override public int produceEnergy(int energy) { - int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerInput(); + int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { int energyUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); pp.receiveEnergy(energyUsed, output.getKey()); - energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerInput(); + energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); if(energy <= 0) { return 0; } } } return energy; } @Override public void setPowerProvider(IPowerProvider provider) { _powerProvider = provider; } @Override public IPowerProvider getPowerProvider() { return _powerProvider; } @Override public void doWork() { } @Override public int powerRequest() { return 0; } }
false
true
public int produceEnergy(int energy) { int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerInput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { int energyUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); pp.receiveEnergy(energyUsed, output.getKey()); energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerInput(); if(energy <= 0) { return 0; } } } return energy; }
public int produceEnergy(int energy) { int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { int energyUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); pp.receiveEnergy(energyUsed, output.getKey()); energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); if(energy <= 0) { return 0; } } } return energy; }
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/internal/operations/OperationValidator.java b/update/org.eclipse.update.core/src/org/eclipse/update/internal/operations/OperationValidator.java index e1510c810..98c1da459 100644 --- a/update/org.eclipse.update.core/src/org/eclipse/update/internal/operations/OperationValidator.java +++ b/update/org.eclipse.update.core/src/org/eclipse/update/internal/operations/OperationValidator.java @@ -1,1368 +1,1368 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.operations; //import java.io.*; //import java.net.*; //import java.nio.channels.*; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProduct; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.PluginVersionIdentifier; import org.eclipse.osgi.util.NLS; import org.eclipse.update.configuration.IConfiguredSite; import org.eclipse.update.configuration.IInstallConfiguration; import org.eclipse.update.configuration.ILocalSite; import org.eclipse.update.configurator.ConfiguratorUtils; import org.eclipse.update.configurator.IPlatformConfiguration; import org.eclipse.update.core.IFeature; import org.eclipse.update.core.IFeatureReference; import org.eclipse.update.core.IImport; import org.eclipse.update.core.IIncludedFeatureReference; import org.eclipse.update.core.IPluginEntry; import org.eclipse.update.core.ISiteFeatureReference; import org.eclipse.update.core.IURLEntry; import org.eclipse.update.core.SiteManager; import org.eclipse.update.core.VersionedIdentifier; import org.eclipse.update.internal.configurator.PlatformConfiguration; import org.eclipse.update.internal.core.Messages; import org.eclipse.update.internal.core.UpdateCore; import org.eclipse.update.operations.IInstallFeatureOperation; import org.eclipse.update.operations.IOperationValidator; import org.osgi.framework.Bundle; /** * */ public class OperationValidator implements IOperationValidator { /** * Checks if the platform configuration has been modified outside this program. * @return the error status, or null if no errors */ public IStatus validatePlatformConfigValid() { ArrayList status = new ArrayList(1); checkPlatformWasModified(status); // report status if (status.size() > 0) return createMultiStatus(Messages.ActivityConstraints_rootMessage, status, IStatus.ERROR); return null; } /* * Called by UI before performing operation. Returns null if no errors, a * status with IStatus.WARNING code when the initial configuration is * broken, or a status with IStatus.ERROR when there the operation * introduces new errors */ public IStatus validatePendingInstall( IFeature oldFeature, IFeature newFeature) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); // check proposed change ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateInstall(oldFeature, newFeature, status); // report status return createCombinedReportStatus(beforeStatus, status); } /* * Called by UI before performing operation */ public IStatus validatePendingUnconfig(IFeature feature) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); // check proposed change ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateUnconfigure(feature, status); // report status return createCombinedReportStatus(beforeStatus, status); } /* * Called by UI before performing operation */ public IStatus validatePendingConfig(IFeature feature) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); // check proposed change ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateConfigure(feature, status); // report status return createCombinedReportStatus(beforeStatus, status); } /** * Called before performing operation. */ public IStatus validatePendingReplaceVersion( IFeature feature, IFeature anotherFeature) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); // check proposed change ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateReplaceVersion(feature, anotherFeature, status); // report status return createCombinedReportStatus(beforeStatus, status); } /* * Called by the UI before doing a revert/ restore operation */ public IStatus validatePendingRevert(IInstallConfiguration config) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); // check proposed change ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateRevert(config, status); // report status return createCombinedReportStatus(beforeStatus, status); } /* * Called by the UI before doing a batched processing of several pending * changes. */ public IStatus validatePendingChanges(IInstallFeatureOperation[] jobs) { // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); checkPlatformWasModified(beforeStatus); // check proposed change ArrayList status = new ArrayList(); validatePendingChanges(jobs, status, beforeStatus); // report status return createCombinedReportStatus(beforeStatus, status); } /* * Called by the UI before doing a batched processing of several pending * changes. */ public RequiredFeaturesResult getRequiredFeatures(IInstallFeatureOperation[] jobs) { RequiredFeaturesResult requiredFeaturesResult = new RequiredFeaturesResult(); // check initial state ArrayList beforeStatus = new ArrayList(); validateInitialState(beforeStatus); checkPlatformWasModified(beforeStatus); // check proposed change ArrayList status = new ArrayList(); Set requiredFeatures = validatePendingChanges(jobs, status, beforeStatus); // report status //return createCombinedReportStatus(beforeStatus, status); requiredFeaturesResult.setRequiredFeatures(requiredFeatures); requiredFeaturesResult.setStatus(createCombinedReportStatus(beforeStatus, status)); return requiredFeaturesResult; } /* * Check the current state. */ public IStatus validateCurrentState() { // check the state ArrayList status = new ArrayList(); checkPlatformWasModified(status); validateInitialState(status); // report status if (status.size() > 0) return createMultiStatus(Messages.ActivityConstraints_rootMessage, status, IStatus.ERROR); return null; } /* * Check to see if we are not broken even before we start */ private static void validateInitialState(ArrayList status) { try { ArrayList features = computeFeatures(); // uncomment this when patch released in boot //checkConfigurationLock(status); checkConstraints(features, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * handle unconfigure */ private static void validateUnconfigure( IFeature feature, ArrayList status) { try { checkSiteReadOnly(feature,status); ArrayList features = computeFeatures(); features = computeFeaturesAfterOperation(features, null, feature); checkConstraints(features, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * handle configure */ private static void validateConfigure(IFeature feature, ArrayList status) { try { checkSiteReadOnly(feature,status); ArrayList features = computeFeatures(); checkOptionalChildConfiguring(feature, status); checkForCycles(feature, null, features); features = computeFeaturesAfterOperation(features, feature, null); checkConstraints(features, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * handle replace version */ private static void validateReplaceVersion( IFeature feature, IFeature anotherFeature, ArrayList status) { try { checkSiteReadOnly(feature,status); ArrayList features = computeFeatures(); checkForCycles(feature, null, features); features = computeFeaturesAfterOperation( features, anotherFeature, feature); checkConstraints(features, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * handle install and update */ private static void validateInstall( IFeature oldFeature, IFeature newFeature, ArrayList status) { try { checkSiteReadOnly(oldFeature,status); ArrayList features = computeFeatures(); checkForCycles(newFeature, null, features); features = computeFeaturesAfterOperation(features, newFeature, oldFeature); checkConstraints(features, status); checkLicense(newFeature, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * handle revert and restore */ private static void validateRevert( IInstallConfiguration config, ArrayList status) { try { // // check the timeline and don't bother // // to check anything else if negative // if (!checkTimeline(config, status)) // return; ArrayList features = computeFeaturesAfterRevert(config); checkConstraints(features, status); checkRevertConstraints(features, status); } catch (CoreException e) { status.add(e.getStatus()); } } /* * Handle one-click changes as a batch */ private static Set validatePendingChanges( IInstallFeatureOperation[] jobs, ArrayList status, ArrayList beforeStatus) { try { ArrayList features = computeFeatures(); ArrayList savedFeatures = features; int nexclusives = 0; // pass 1: see if we can process the entire "batch" ArrayList tmpStatus = new ArrayList(); for (int i = 0; i < jobs.length; i++) { IInstallFeatureOperation job = jobs[i]; IFeature newFeature = job.getFeature(); IFeature oldFeature = job.getOldFeature(); checkLicense(newFeature, status); if (jobs.length > 1 && newFeature.isExclusive()) { nexclusives++; status.add( createStatus( newFeature, FeatureStatus.CODE_EXCLUSIVE, Messages.ActivityConstraints_exclusive)); continue; } checkForCycles(newFeature, null, features); features = computeFeaturesAfterOperation( features, newFeature, oldFeature); } if (nexclusives > 0) return Collections.EMPTY_SET; checkConstraints(features, tmpStatus); if (tmpStatus.size() == 0) // the whole "batch" is OK return Collections.EMPTY_SET; // pass 2: we have conflicts features = savedFeatures; for (int i = 0; i < jobs.length; i++) { IInstallFeatureOperation job = jobs[i]; IFeature newFeature = job.getFeature(); IFeature oldFeature = job.getOldFeature(); features = computeFeaturesAfterOperation( features, newFeature, oldFeature); Set result = checkConstraints(features, status); if (status.size() > 0 && !isBetterStatus(beforeStatus, status)) { // bug 75613 // IStatus conflict = // createStatus( // newFeature, // FeatureStatus.CODE_OTHER, // Policy.bind(KEY_CONFLICT)); // status.add(0, conflict); return result; } } } catch (CoreException e) { status.add(e.getStatus()); } return Collections.EMPTY_SET; } private static void checkPlatformWasModified(ArrayList status) { try { // checks if the platform has been modified outside this eclipse instance IPlatformConfiguration platformConfig = ConfiguratorUtils.getCurrentPlatformConfiguration(); long currentTimeStamp = platformConfig.getChangeStamp(); // get the last modified value for this config, from this process point of view if (platformConfig instanceof PlatformConfiguration) currentTimeStamp = ((PlatformConfiguration)platformConfig).getConfiguration().lastModified(); // get the real last modified value URL platformXML = platformConfig.getConfigurationLocation(); long actualTimeStamp = currentTimeStamp; if ("file".equals(platformXML.getProtocol())) //$NON-NLS-1$ actualTimeStamp = new File(platformXML.getFile()).lastModified(); else { URLConnection connection = platformXML.openConnection(); actualTimeStamp = connection.getLastModified(); } if (currentTimeStamp != actualTimeStamp) status.add(createStatus( null, FeatureStatus.CODE_OTHER, Messages.ActivityConstraints_platformModified)); } catch (IOException e) { // ignore } } private static void checkSiteReadOnly(IFeature feature, ArrayList status) { if(feature == null){ return; } IConfiguredSite csite = feature.getSite().getCurrentConfiguredSite(); if (csite != null && !csite.isUpdatable()) status.add(createStatus(feature, FeatureStatus.CODE_OTHER, NLS.bind(Messages.ActivityConstraints_readOnly, (new String[] { csite.getSite().getURL().toExternalForm() })))); } /* * Compute a list of configured features */ private static ArrayList computeFeatures() throws CoreException { return computeFeatures(true); } /* * Compute a list of configured features */ private static ArrayList computeFeatures(boolean configuredOnly) throws CoreException { ArrayList features = new ArrayList(); ILocalSite localSite = SiteManager.getLocalSite(); IInstallConfiguration config = localSite.getCurrentConfiguration(); IConfiguredSite[] csites = config.getConfiguredSites(); for (int i = 0; i < csites.length; i++) { IConfiguredSite csite = csites[i]; IFeatureReference[] crefs; if (configuredOnly) crefs = csite.getConfiguredFeatures(); else crefs = csite.getSite().getFeatureReferences(); for (int j = 0; j < crefs.length; j++) { IFeatureReference cref = crefs[j]; IFeature cfeature = cref.getFeature(null); features.add(cfeature); } } return features; } /* * Compute the nested feature subtree starting at the specified base * feature */ public static ArrayList computeFeatureSubtree( IFeature top, IFeature feature, ArrayList features, boolean tolerateMissingChildren, ArrayList configuredFeatures, ArrayList visitedFeatures) throws CoreException { // check arguments if (top == null) return features; if (feature == null) feature = top; if (features == null) features = new ArrayList(); if (visitedFeatures == null) visitedFeatures = new ArrayList(); // check for <includes> cycle if (visitedFeatures.contains(feature)) { IStatus status = createStatus(top, FeatureStatus.CODE_CYCLE, Messages.ActivityConstraints_cycle); throw new CoreException(status); } else { // keep track of visited features so we can detect cycles visitedFeatures.add(feature); } // return specified base feature and all its children if (!features.contains(feature)) features.add(feature); IIncludedFeatureReference[] children = feature.getIncludedFeatureReferences(); for (int i = 0; i < children.length; i++) { try { IFeature child = children[i].getFeature(null); features = computeFeatureSubtree( top, child, features, tolerateMissingChildren, null, visitedFeatures); } catch (CoreException e) { if (!children[i].isOptional() && !tolerateMissingChildren) throw e; } } // no cycles for this feature during DFS visitedFeatures.remove(feature); return features; } private static void checkLicense(IFeature feature, ArrayList status) { IURLEntry licenseEntry = feature.getLicense(); if (licenseEntry != null) { String license = licenseEntry.getAnnotation(); if (license != null && license.trim().length() > 0) return; } status.add( createStatus(feature, FeatureStatus.CODE_OTHER, Messages.ActivityConstraints_noLicense)); } /* * Compute a list of features that will be configured after the operation */ private static ArrayList computeFeaturesAfterOperation( ArrayList features, IFeature add, IFeature remove) throws CoreException { ArrayList addTree = computeFeatureSubtree(add, null, null, false, /* do not tolerate missing children */ features, null); ArrayList removeTree = computeFeatureSubtree( remove, null, null, true /* tolerate missing children */, null, null ); if (remove != null) { // Patches to features are removed together with // those features. Include them in the list. contributePatchesFor(removeTree, features, removeTree); } if (remove != null) features.removeAll(removeTree); if (add != null) features.addAll(addTree); return features; } private static void contributePatchesFor( ArrayList removeTree, ArrayList features, ArrayList result) throws CoreException { for (int i = 0; i < removeTree.size(); i++) { IFeature feature = (IFeature) removeTree.get(i); contributePatchesFor(feature, features, result); } } private static void contributePatchesFor( IFeature feature, ArrayList features, ArrayList result) throws CoreException { for (int i = 0; i < features.size(); i++) { IFeature candidate = (IFeature) features.get(i); if (UpdateUtils.isPatch(feature, candidate)) { ArrayList removeTree = computeFeatureSubtree(candidate, null, null, true,null,null); result.addAll(removeTree); } } } /* * Compute a list of features that will be configured after performing the * revert */ private static ArrayList computeFeaturesAfterRevert(IInstallConfiguration config) throws CoreException { ArrayList list = new ArrayList(); IConfiguredSite[] csites = config.getConfiguredSites(); for (int i = 0; i < csites.length; i++) { IConfiguredSite csite = csites[i]; IFeatureReference[] features = csite.getConfiguredFeatures(); for (int j = 0; j < features.length; j++) { list.add(features[j].getFeature(null)); } } return list; } /* * Compute a list of plugin entries for the specified features. */ private static ArrayList computePluginsForFeatures(ArrayList features) throws CoreException { if (features == null) return new ArrayList(); HashMap plugins = new HashMap(); for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); IPluginEntry[] entries = feature.getPluginEntries(); for (int j = 0; j < entries.length; j++) { IPluginEntry entry = entries[j]; plugins.put(entry.getVersionedIdentifier(), entry); } } ArrayList result = new ArrayList(); result.addAll(plugins.values()); return result; } /** * Check for feature cycles: * - visit feature * - if feature is in the cycle candidates list, then cycle found, else add it to candidates list * - DFS children * - when return from DFS remove the feature from the candidates list */ private static void checkForCycles( IFeature feature, ArrayList candidates, ArrayList configuredFeatures) throws CoreException { // check arguments if (feature == null) return; if (configuredFeatures == null) configuredFeatures = new ArrayList(); if (candidates == null) candidates = new ArrayList(); // check for <includes> cycle if (candidates.contains(feature)) { String msg = NLS.bind(Messages.ActivityConstraints_cycle, (new String[] {feature.getLabel(), feature.getVersionedIdentifier().toString()})); IStatus status = createStatus(feature, FeatureStatus.CODE_CYCLE, msg); throw new CoreException(status); } // potential candidate candidates.add(feature); // recursively, check cycles with children IIncludedFeatureReference[] children = feature.getIncludedFeatureReferences(); for (int i = 0; i < children.length; i++) { try { IFeature child = children[i].getFeature(null); checkForCycles(child, candidates, configuredFeatures); } catch (CoreException e) { if (!children[i].isOptional()) throw e; } } // no longer a candidate, because no cycles with children candidates.remove(feature); } /* * validate constraints */ private static Set checkConstraints(ArrayList features, ArrayList status) throws CoreException { if (features == null) return Collections.EMPTY_SET; ArrayList plugins = computePluginsForFeatures(features); checkEnvironment(features, status); checkPlatformFeature(features, plugins, status); checkPrimaryFeature(features, plugins, status); return checkPrereqs(features, plugins, status); } /* * Verify all features are either portable, or match the current * environment */ private static void checkEnvironment( ArrayList features, ArrayList status) { String os = Platform.getOS(); String ws = Platform.getWS(); String arch = Platform.getOSArch(); for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); ArrayList fos = createList(feature.getOS()); ArrayList fws = createList(feature.getWS()); ArrayList farch = createList(feature.getOSArch()); if (fos.size() > 0) { if (!fos.contains(os)) { IStatus s = createStatus(feature, FeatureStatus.CODE_ENVIRONMENT, Messages.ActivityConstraints_os); if (!status.contains(s)) status.add(s); continue; } } if (fws.size() > 0) { if (!fws.contains(ws)) { IStatus s = createStatus(feature, FeatureStatus.CODE_ENVIRONMENT, Messages.ActivityConstraints_ws); if (!status.contains(s)) status.add(s); continue; } } if (farch.size() > 0) { if (!farch.contains(arch)) { IStatus s = createStatus(feature, FeatureStatus.CODE_ENVIRONMENT, Messages.ActivityConstraints_arch); if (!status.contains(s)) status.add(s); continue; } } } } /* * Verify we end up with a version of platform configured */ private static void checkPlatformFeature( ArrayList features, ArrayList plugins, ArrayList status) { // find the plugin that defines the product IProduct product = Platform.getProduct(); if (product == null) return; // normally this shouldn't happen Bundle primaryBundle = product.getDefiningBundle(); // check if that plugin is among the resulting plugins boolean found = false; for (int j = 0; j < plugins.size(); j++) { IPluginEntry plugin = (IPluginEntry) plugins.get(j); if (primaryBundle.getSymbolicName().equals(plugin.getVersionedIdentifier().getIdentifier())) { found = true; break; } } if (!found) { IStatus s = createStatus(null, FeatureStatus.CODE_OTHER, Messages.ActivityConstraints_platform); if (!status.contains(s)) status.add(s); } } /* * Verify we end up with a version of primary feature configured */ private static void checkPrimaryFeature( ArrayList features, ArrayList plugins, ArrayList status) { String featureId = ConfiguratorUtils .getCurrentPlatformConfiguration() .getPrimaryFeatureIdentifier(); if (featureId != null) { // primary feature is defined for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); if (featureId .equals(feature.getVersionedIdentifier().getIdentifier())) return; } IStatus s = createStatus(null, FeatureStatus.CODE_OTHER, Messages.ActivityConstraints_primary); if (!status.contains(s)) status.add(s); } else { // check if the product still ends up contributed // find the plugin that defines the product IProduct product = Platform.getProduct(); if (product == null) return; // normally this shouldn't happen Bundle primaryBundle = product.getDefiningBundle(); // check if that plugin is among the resulting plugins for (int j = 0; j < plugins.size(); j++) { IPluginEntry plugin = (IPluginEntry) plugins.get(j); if (primaryBundle.getSymbolicName().equals(plugin.getVersionedIdentifier().getIdentifier())) { return; // product found } } IStatus s = createStatus(null, FeatureStatus.CODE_OTHER, Messages.ActivityConstraints_primary); if (!status.contains(s)) status.add(s); } } /* * Verify we do not break prereqs */ private static Set checkPrereqs( ArrayList features, ArrayList plugins, ArrayList status) { HashSet result = new HashSet(); for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); IImport[] imports = feature.getImports(); for (int j = 0; j < imports.length; j++) { IImport iimport = imports[j]; // for each import determine plugin or feature, version, match // we need VersionedIdentifier iid = iimport.getVersionedIdentifier(); String id = iid.getIdentifier(); PluginVersionIdentifier version = iid.getVersion(); boolean featurePrereq = iimport.getKind() == IImport.KIND_FEATURE; boolean ignoreVersion = version.getMajorComponent() == 0 && version.getMinorComponent() == 0 && version.getServiceComponent() == 0; int rule = iimport.getRule(); if (rule == IImport.RULE_NONE) rule = IImport.RULE_COMPATIBLE; boolean found = false; ArrayList candidates; if (featurePrereq) candidates = features; else candidates = plugins; for (int k = 0; k < candidates.size(); k++) { VersionedIdentifier cid; if (featurePrereq) { // the candidate is a feature IFeature candidate = (IFeature) candidates.get(k); // skip self if (feature.equals(candidate)) continue; cid = candidate.getVersionedIdentifier(); } else { // the candidate is a plug-in IPluginEntry plugin = (IPluginEntry) candidates.get(k); cid = plugin.getVersionedIdentifier(); } PluginVersionIdentifier cversion = cid.getVersion(); if (id.equals(cid.getIdentifier())) { // have a candidate if (ignoreVersion) found = true; else if ( rule == IImport.RULE_PERFECT && cversion.isPerfect(version)) found = true; else if ( rule == IImport.RULE_EQUIVALENT && cversion.isEquivalentTo(version)) found = true; else if ( rule == IImport.RULE_COMPATIBLE && cversion.isCompatibleWith(version)) found = true; else if ( rule == IImport.RULE_GREATER_OR_EQUAL && cversion.isGreaterOrEqualTo(version)) found = true; } if (found) break; } if (!found) { // report status String target = featurePrereq ? Messages.ActivityConstaints_prereq_feature : Messages.ActivityConstaints_prereq_plugin; int errorCode = featurePrereq ? FeatureStatus.CODE_PREREQ_FEATURE : FeatureStatus.CODE_PREREQ_PLUGIN; String msg = NLS.bind(Messages.ActivityConstraints_prereq, (new String[] { target, id })); if (!ignoreVersion) { if (rule == IImport.RULE_PERFECT) msg = NLS.bind(Messages.ActivityConstraints_prereqPerfect, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_EQUIVALENT) msg = NLS.bind(Messages.ActivityConstraints_prereqEquivalent, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_COMPATIBLE) msg = NLS.bind(Messages.ActivityConstraints_prereqCompatible, (new String[] { target, - feature.getLabel(), + id, version.toString()})); else if (rule == IImport.RULE_GREATER_OR_EQUAL) msg = NLS.bind(Messages.ActivityConstraints_prereqGreaterOrEqual, (new String[] { target, id, version.toString()})); } IStatus s = createStatus(feature, errorCode, msg); result.add(new InternalImport(iimport)); if (!status.contains(s)) status.add(s); } } } return result; } /* * Verify we end up with valid nested features after revert */ private static void checkRevertConstraints( ArrayList features, ArrayList status) { for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); try { computeFeatureSubtree( feature, null, null, false /* do not tolerate missing children */, null, null ); } catch (CoreException e) { status.add(e.getStatus()); } } } /* * Verify that a parent of an optional child is configured before we allow * the child to be configured as well */ private static void checkOptionalChildConfiguring( IFeature feature, ArrayList status) throws CoreException { ILocalSite localSite = SiteManager.getLocalSite(); IInstallConfiguration config = localSite.getCurrentConfiguration(); IConfiguredSite[] csites = config.getConfiguredSites(); boolean included = false; for (int i = 0; i < csites.length; i++) { IConfiguredSite csite = csites[i]; ISiteFeatureReference[] crefs = csite.getSite().getFeatureReferences(); for (int j = 0; j < crefs.length; j++) { IFeatureReference cref = crefs[j]; IFeature cfeature = null; try { cfeature = cref.getFeature(null); } catch (CoreException e) { //FIXME: cannot ask 'isOptional' here // Ignore missing optional feature. /* * if (cref.isOptional()) continue; */ throw e; } if (isParent(cfeature, feature, true)) { // Included in at least one feature as optional included = true; if (csite.isConfigured(cfeature)) { // At least one feature parent // is enabled - it is OK to // configure optional child. return; } } } } if (included) { // feature is included as optional but // no parent is currently configured. String msg = Messages.ActivityConstraints_optionalChild; status.add(createStatus(feature, FeatureStatus.CODE_OPTIONAL_CHILD, msg)); } else { //feature is root - can be configured } } // // /** // * Checks if the configuration is locked by other instances // * // * @param status // */ // private static void checkConfigurationLock(ArrayList status) { // IPlatformConfiguration config = // BootLoader.getCurrentPlatformConfiguration(); // URL configURL = config.getConfigurationLocation(); // if (!"file".equals(configURL.getProtocol())) { // status.add( // createStatus( // null, // "Configuration location is not writable:" + configURL)); // return; // } // String locationString = configURL.getFile(); // File configDir = new File(locationString); // if (!configDir.isDirectory()) // configDir = configDir.getParentFile(); // if (!configDir.exists()) { // status.add( // createStatus(null, "Configuration location does not exist")); // return; // } // File locksDir = new File(configDir, "locks"); // // check all the possible lock files // File[] lockFiles = locksDir.listFiles(); // File configLock = BootLoader.getCurrentPlatformConfiguration().getLockFile(); // for (int i = 0; i < lockFiles.length; i++) { // if (lockFiles[i].equals(configLock)) // continue; // try { // RandomAccessFile raf = new RandomAccessFile(lockFiles[i], "rw"); // FileChannel channel = raf.getChannel(); // System.out.println(channel.isOpen()); // FileLock lock = channel.tryLock(); // if (lock == null){ // // there is another eclipse instance running // raf.close(); // status.add( // createStatus( // null, // "Another instance is running, please close it before performing any configuration operations")); // return; // } // // } catch (Exception e) { // status.add(createStatus(null, "Failed to create lock:"+lockFiles[i])); // return; // } // } // } private static boolean isParent( IFeature candidate, IFeature feature, boolean optionalOnly) throws CoreException { IIncludedFeatureReference[] refs = candidate.getIncludedFeatureReferences(); for (int i = 0; i < refs.length; i++) { IIncludedFeatureReference child = refs[i]; VersionedIdentifier fvid = feature.getVersionedIdentifier(); VersionedIdentifier cvid = child.getVersionedIdentifier(); if (fvid.getIdentifier().equals(cvid.getIdentifier()) == false) continue; // same ID PluginVersionIdentifier fversion = fvid.getVersion(); PluginVersionIdentifier cversion = cvid.getVersion(); if (fversion.equals(cversion)) { // included and matched; return true if optionality is not // important or it is and the inclusion is optional return optionalOnly == false || child.isOptional(); } } return false; } // private static boolean checkTimeline( // IInstallConfiguration config, // ArrayList status) { // try { // ILocalSite lsite = SiteManager.getLocalSite(); // IInstallConfiguration cconfig = lsite.getCurrentConfiguration(); // if (cconfig.getTimeline() != config.getTimeline()) { // // Not the same timeline - cannot revert // String msg = // UpdateUtils.getFormattedMessage( // KEY_WRONG_TIMELINE, // config.getLabel()); // status.add(createStatus(null, FeatureStatus.CODE_OTHER, msg)); // return false; // } // } catch (CoreException e) { // status.add(e.getStatus()); // } // return true; // } private static IStatus createMultiStatus( String message, ArrayList children, int code) { IStatus[] carray = (IStatus[]) children.toArray(new IStatus[children.size()]); return new MultiStatus( UpdateCore.getPlugin().getBundle().getSymbolicName(), code, carray, message, null); } private static IStatus createStatus(IFeature feature, int errorCode, String message) { String fullMessage; if (feature == null) fullMessage = message; else { PluginVersionIdentifier version = feature.getVersionedIdentifier().getVersion(); fullMessage = NLS.bind(Messages.ActivityConstraints_childMessage, (new String[] { feature.getLabel(), version.toString(), message })); } return new FeatureStatus( feature, IStatus.ERROR, UpdateCore.getPlugin().getBundle().getSymbolicName(), errorCode, fullMessage, null); } // private static IStatus createReportStatus(ArrayList beforeStatus, // ArrayList status) { // // report status // if (status.size() > 0) { // if (beforeStatus.size() > 0) // return createMultiStatus(KEY_ROOT_MESSAGE_INIT, // beforeStatus,IStatus.ERROR); // else // return createMultiStatus(KEY_ROOT_MESSAGE, status,IStatus.ERROR); // } // return null; // } private static IStatus createCombinedReportStatus( ArrayList beforeStatus, ArrayList status) { if (beforeStatus.size() == 0) { // good initial config if (status.size() == 0) { return null; // all fine } else { return createMultiStatus(Messages.ActivityConstraints_rootMessage, status, IStatus.ERROR); // error after operation } } else { // beforeStatus.size() > 0 : initial config errors if (status.size() == 0) { return null; // errors will be fixed } else { if (isBetterStatus(beforeStatus, status)) { return createMultiStatus( Messages.ActivityConstraints_warning, beforeStatus, IStatus.WARNING); // errors may be fixed } else { ArrayList combined = new ArrayList(); combined.add( createMultiStatus( Messages.ActivityConstraints_beforeMessage, beforeStatus, IStatus.ERROR)); combined.add( createMultiStatus( Messages.ActivityConstraints_afterMessage, status, IStatus.ERROR)); return createMultiStatus( Messages.ActivityConstraints_rootMessageInitial, combined, IStatus.ERROR); } } } } private static ArrayList createList(String commaSeparatedList) { ArrayList list = new ArrayList(); if (commaSeparatedList != null) { StringTokenizer t = new StringTokenizer(commaSeparatedList.trim(), ","); //$NON-NLS-1$ while (t.hasMoreTokens()) { String token = t.nextToken().trim(); if (!token.equals("")) //$NON-NLS-1$ list.add(token); } } return list; } /** * Returns true if status is a subset of beforeStatus * * @param beforeStatus * @param status * @return */ private static boolean isBetterStatus( ArrayList beforeStatus, ArrayList status) { // if no status at all, then it's a subset if (status == null || status.size() == 0) return true; // there is some status, so if there is no initial status, then it's // not a subset if (beforeStatus == null || beforeStatus.size() == 0) return false; // quick check if (beforeStatus.size() < status.size()) return false; // check if all the status elements appear in the original status for (int i = 0; i < status.size(); i++) { IStatus s = (IStatus) status.get(i); // if this is not a feature status, something is wrong, so return // false if (!(s instanceof FeatureStatus)) return false; FeatureStatus fs = (FeatureStatus) s; // check against all status elements boolean found = false; for (int j = 0; !found && j < beforeStatus.size(); j++) { if (fs.equals(beforeStatus.get(j))) found = true; } if (!found) return false; } return true; } public class RequiredFeaturesResult { private IStatus status; private Set requiredFeatures; public Set getRequiredFeatures() { return requiredFeatures; } public void setRequiredFeatures(Set requiredFeatures) { this.requiredFeatures = requiredFeatures; } public void addRequiredFeatures(Set requiredFeatures) { if (requiredFeatures == null) { requiredFeatures = new HashSet(); } this.requiredFeatures.addAll(requiredFeatures); } public IStatus getStatus() { return status; } public void setStatus(IStatus status) { this.status = status; } } public static class InternalImport { private IImport iimport; public InternalImport(IImport iimport) { this.iimport = iimport; } public IImport getImport() { return iimport; } public void setImport(IImport iimport) { this.iimport = iimport; } public boolean equals(Object object) { if ( ( object == null) || !(object instanceof InternalImport)) return false; if ( object == this) return true; return iimport.getVersionedIdentifier().equals( ((InternalImport)object).getImport().getVersionedIdentifier()) && (getImport().getRule() == ((InternalImport)object).getImport().getRule()); } public int hashCode() { return iimport.getVersionedIdentifier().hashCode() * iimport.getRule(); } } }
true
true
private static Set checkPrereqs( ArrayList features, ArrayList plugins, ArrayList status) { HashSet result = new HashSet(); for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); IImport[] imports = feature.getImports(); for (int j = 0; j < imports.length; j++) { IImport iimport = imports[j]; // for each import determine plugin or feature, version, match // we need VersionedIdentifier iid = iimport.getVersionedIdentifier(); String id = iid.getIdentifier(); PluginVersionIdentifier version = iid.getVersion(); boolean featurePrereq = iimport.getKind() == IImport.KIND_FEATURE; boolean ignoreVersion = version.getMajorComponent() == 0 && version.getMinorComponent() == 0 && version.getServiceComponent() == 0; int rule = iimport.getRule(); if (rule == IImport.RULE_NONE) rule = IImport.RULE_COMPATIBLE; boolean found = false; ArrayList candidates; if (featurePrereq) candidates = features; else candidates = plugins; for (int k = 0; k < candidates.size(); k++) { VersionedIdentifier cid; if (featurePrereq) { // the candidate is a feature IFeature candidate = (IFeature) candidates.get(k); // skip self if (feature.equals(candidate)) continue; cid = candidate.getVersionedIdentifier(); } else { // the candidate is a plug-in IPluginEntry plugin = (IPluginEntry) candidates.get(k); cid = plugin.getVersionedIdentifier(); } PluginVersionIdentifier cversion = cid.getVersion(); if (id.equals(cid.getIdentifier())) { // have a candidate if (ignoreVersion) found = true; else if ( rule == IImport.RULE_PERFECT && cversion.isPerfect(version)) found = true; else if ( rule == IImport.RULE_EQUIVALENT && cversion.isEquivalentTo(version)) found = true; else if ( rule == IImport.RULE_COMPATIBLE && cversion.isCompatibleWith(version)) found = true; else if ( rule == IImport.RULE_GREATER_OR_EQUAL && cversion.isGreaterOrEqualTo(version)) found = true; } if (found) break; } if (!found) { // report status String target = featurePrereq ? Messages.ActivityConstaints_prereq_feature : Messages.ActivityConstaints_prereq_plugin; int errorCode = featurePrereq ? FeatureStatus.CODE_PREREQ_FEATURE : FeatureStatus.CODE_PREREQ_PLUGIN; String msg = NLS.bind(Messages.ActivityConstraints_prereq, (new String[] { target, id })); if (!ignoreVersion) { if (rule == IImport.RULE_PERFECT) msg = NLS.bind(Messages.ActivityConstraints_prereqPerfect, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_EQUIVALENT) msg = NLS.bind(Messages.ActivityConstraints_prereqEquivalent, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_COMPATIBLE) msg = NLS.bind(Messages.ActivityConstraints_prereqCompatible, (new String[] { target, feature.getLabel(), version.toString()})); else if (rule == IImport.RULE_GREATER_OR_EQUAL) msg = NLS.bind(Messages.ActivityConstraints_prereqGreaterOrEqual, (new String[] { target, id, version.toString()})); } IStatus s = createStatus(feature, errorCode, msg); result.add(new InternalImport(iimport)); if (!status.contains(s)) status.add(s); } } } return result; }
private static Set checkPrereqs( ArrayList features, ArrayList plugins, ArrayList status) { HashSet result = new HashSet(); for (int i = 0; i < features.size(); i++) { IFeature feature = (IFeature) features.get(i); IImport[] imports = feature.getImports(); for (int j = 0; j < imports.length; j++) { IImport iimport = imports[j]; // for each import determine plugin or feature, version, match // we need VersionedIdentifier iid = iimport.getVersionedIdentifier(); String id = iid.getIdentifier(); PluginVersionIdentifier version = iid.getVersion(); boolean featurePrereq = iimport.getKind() == IImport.KIND_FEATURE; boolean ignoreVersion = version.getMajorComponent() == 0 && version.getMinorComponent() == 0 && version.getServiceComponent() == 0; int rule = iimport.getRule(); if (rule == IImport.RULE_NONE) rule = IImport.RULE_COMPATIBLE; boolean found = false; ArrayList candidates; if (featurePrereq) candidates = features; else candidates = plugins; for (int k = 0; k < candidates.size(); k++) { VersionedIdentifier cid; if (featurePrereq) { // the candidate is a feature IFeature candidate = (IFeature) candidates.get(k); // skip self if (feature.equals(candidate)) continue; cid = candidate.getVersionedIdentifier(); } else { // the candidate is a plug-in IPluginEntry plugin = (IPluginEntry) candidates.get(k); cid = plugin.getVersionedIdentifier(); } PluginVersionIdentifier cversion = cid.getVersion(); if (id.equals(cid.getIdentifier())) { // have a candidate if (ignoreVersion) found = true; else if ( rule == IImport.RULE_PERFECT && cversion.isPerfect(version)) found = true; else if ( rule == IImport.RULE_EQUIVALENT && cversion.isEquivalentTo(version)) found = true; else if ( rule == IImport.RULE_COMPATIBLE && cversion.isCompatibleWith(version)) found = true; else if ( rule == IImport.RULE_GREATER_OR_EQUAL && cversion.isGreaterOrEqualTo(version)) found = true; } if (found) break; } if (!found) { // report status String target = featurePrereq ? Messages.ActivityConstaints_prereq_feature : Messages.ActivityConstaints_prereq_plugin; int errorCode = featurePrereq ? FeatureStatus.CODE_PREREQ_FEATURE : FeatureStatus.CODE_PREREQ_PLUGIN; String msg = NLS.bind(Messages.ActivityConstraints_prereq, (new String[] { target, id })); if (!ignoreVersion) { if (rule == IImport.RULE_PERFECT) msg = NLS.bind(Messages.ActivityConstraints_prereqPerfect, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_EQUIVALENT) msg = NLS.bind(Messages.ActivityConstraints_prereqEquivalent, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_COMPATIBLE) msg = NLS.bind(Messages.ActivityConstraints_prereqCompatible, (new String[] { target, id, version.toString()})); else if (rule == IImport.RULE_GREATER_OR_EQUAL) msg = NLS.bind(Messages.ActivityConstraints_prereqGreaterOrEqual, (new String[] { target, id, version.toString()})); } IStatus s = createStatus(feature, errorCode, msg); result.add(new InternalImport(iimport)); if (!status.contains(s)) status.add(s); } } } return result; }
diff --git a/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuRenderer.java b/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuRenderer.java index 9695e30..4740b73 100644 --- a/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuRenderer.java +++ b/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuRenderer.java @@ -1,358 +1,358 @@ package brix.plugin.menu.tile; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.wicket.Response; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.html.WebComponent; import org.apache.wicket.model.IModel; import org.apache.wicket.util.string.Strings; import brix.auth.Action.Context; import brix.jcr.wrapper.BrixNode; import brix.plugin.menu.Menu; import brix.plugin.menu.Menu.ChildEntry; import brix.plugin.menu.Menu.Entry; import brix.plugin.site.SitePlugin; import brix.web.generic.IGenericComponent; import brix.web.nodepage.BrixNodeWebPage; import brix.web.nodepage.BrixPageParameters; import brix.web.reference.Reference; import brix.web.reference.Reference.Type; /** * Component used to render the menu * * @author igor.vaynberg * */ public class MenuRenderer extends WebComponent implements IGenericComponent<BrixNode> { private static final long serialVersionUID = 1L; /** * Constructor * * @param id * @param model */ public MenuRenderer(String id, IModel<BrixNode> model) { super(id, model); } /** {@inheritDoc} */ @Override protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { MenuContainer container = new MenuContainer(); container.load(getModelObject()); Set<ChildEntry> selected = getSelectedItems(container.getMenu()); // how many levels to skip to start rendering int skipLevels = container.getStartAtLevel() != null ? container.getStartAtLevel() : 0; // how many levels should be rendered int renderLevels = container.getRenderLevels() != null ? container.getRenderLevels() : Integer.MAX_VALUE; Response response = getResponse(); renderEntry(container, container.getMenu().getRoot(), response, selected, skipLevels, renderLevels); } private void renderEntry(MenuContainer container, Entry entry, Response response, Set<ChildEntry> selected, int skipLevels, int renderLevels) { if (renderLevels <= 0) { return; } if (skipLevels <= 0) { boolean outer = skipLevels == 0; String klass = ""; if (outer && !Strings.isEmpty(container.getOuterContainerStyleClass())) { klass = " class='" + container.getOuterContainerStyleClass() + "'"; } else if (!outer && !Strings.isEmpty(container.getInnerContainerStyleClass())) { klass = " class='" + container.getInnerContainerStyleClass() + "'"; } response.write("\n<ul"); response.write(klass); response.write(">\n"); } for (ChildEntry e : entry.getChildren()) { BrixNode node = getNode(e); if (node == null || SitePlugin.get().canViewNode(node, Context.PRESENTATION)) { renderChild(container, e, response, selected, skipLevels, renderLevels); } } if (skipLevels <= 0) { response.write("</ul>\n"); } } private BrixNode getNode(ChildEntry entry) { if (entry.getReference() != null && !entry.getReference().isEmpty() && entry.getReference().getType() == Type.NODE) { return entry.getReference().getNodeModel().getObject(); } else { List<ChildEntry> children = entry.getChildren(); if (children != null && !children.isEmpty()) { return getNode(children.iterator().next()); } else { return null; } } } private String getUrl(ChildEntry entry) { if (entry.getReference() != null && !entry.getReference().isEmpty()) { return entry.getReference().generateUrl(); } else { List<ChildEntry> children = entry.getChildren(); if (children != null && !children.isEmpty()) { return getUrl(children.iterator().next()); } else { return "#"; } } } private boolean anyChildSelected(ChildEntry entry, Set<ChildEntry> selectedSet) { if (entry.getChildren() != null) { for (ChildEntry e : entry.getChildren()) { if (selectedSet.contains(e)) { return true; } } } return false; } private void renderChild(MenuContainer container, ChildEntry entry, Response response, Set<ChildEntry> selectedSet, int skipLevels, int renderLevels) { boolean selected = selectedSet.contains(entry); boolean anyChildren = selected && anyChildren(entry); if (skipLevels <= 0) { String listItemCssClass = ""; String anchorCssClass = ""; if (selected && !Strings.isEmpty(container.getSelectedItemStyleClass())) { listItemCssClass = container.getSelectedItemStyleClass(); anchorCssClass = container.getSelectedItemStyleClass(); } if (anyChildren && selected && anyChildSelected(entry, selectedSet) && !Strings.isEmpty(container.getItemWithSelectedChildStyleClass())) { listItemCssClass = container.getItemWithSelectedChildStyleClass(); } if (!Strings.isEmpty(entry.getCssClass())) { if (!Strings.isEmpty(listItemCssClass)) { listItemCssClass += " "; } listItemCssClass += entry.getCssClass(); } response.write("\n<li"); if (!Strings.isEmpty(listItemCssClass)) { response.write(" class=\""); response.write(listItemCssClass); response.write("\""); } response.write(">"); final String url = getUrl(entry); response.write("<a"); if (!Strings.isEmpty(anchorCssClass)) { - response.write("class=\""); + response.write(" class=\""); response.write(anchorCssClass); response.write("\""); } response.write(" href=\""); response.write(url); response.write("\"><span>"); // TODO. escape or not (probably a property would be nice? response.write(entry.getTitle()); response.write("</span></a>"); } // only decrement skip levels for child if current is begger than 0 int childSkipLevels = skipLevels - 1; // only decrement render levels when we are already rendering int childRenderLevels = skipLevels <= 0 ? renderLevels - 1 : renderLevels; if (anyChildren) { renderEntry(container, entry, response, selectedSet, childSkipLevels, childRenderLevels); } if (skipLevels == 0) { response.write("</li>\n"); } } private boolean anyChildren(ChildEntry entry) { if (entry.getChildren() != null) { for (ChildEntry e : entry.getChildren()) { BrixNode node = getNode(e); if (node == null || SitePlugin.get().canViewNode(node, Context.PRESENTATION)) { return true; } } } return false; } private boolean isSelected(Reference reference, String url) { boolean eq = false; BrixNodeWebPage page = (BrixNodeWebPage)getPage(); if (reference.getType() == Type.NODE) { eq = page.getModel().equals(reference.getNodeModel()) && comparePageParameters(page.getBrixPageParameters(), reference.getParameters()); } else { eq = url.equals(reference.getUrl()) && comparePageParameters(page.getBrixPageParameters(), reference.getParameters()); } return eq; } private boolean comparePageParameters(BrixPageParameters page, BrixPageParameters fromReference) { if (fromReference == null || (fromReference.getIndexedParamsCount() == 0 && fromReference.getQueryParamKeys() .isEmpty())) { return true; } else { return BrixPageParameters.equals(page, fromReference); } } private boolean isSelected(ChildEntry entry) { final String url = "/" + getRequest().getPath(); Reference ref = entry.getReference(); if (ref == null) { return false; } else { return isSelected(ref, url); } } private void checkSelected(ChildEntry entry, Set<ChildEntry> selectedSet) { if (isSelected(entry)) { for (Entry e = entry; e instanceof ChildEntry; e = e.getParent()) { selectedSet.add((ChildEntry)e); } } for (ChildEntry e : entry.getChildren()) { checkSelected(e, selectedSet); } } Set<ChildEntry> getSelectedItems(Menu menu) { Set<ChildEntry> result = new HashSet<ChildEntry>(); for (ChildEntry e : menu.getRoot().getChildren()) { checkSelected(e, result); } return result; } @SuppressWarnings("unchecked") public IModel<BrixNode> getModel() { return (IModel<BrixNode>)getDefaultModel(); } public BrixNode getModelObject() { return (BrixNode)getDefaultModelObject(); } public void setModel(IModel<BrixNode> model) { setDefaultModel(model); } public void setModelObject(BrixNode object) { setDefaultModelObject(object); } }
true
true
private void renderChild(MenuContainer container, ChildEntry entry, Response response, Set<ChildEntry> selectedSet, int skipLevels, int renderLevels) { boolean selected = selectedSet.contains(entry); boolean anyChildren = selected && anyChildren(entry); if (skipLevels <= 0) { String listItemCssClass = ""; String anchorCssClass = ""; if (selected && !Strings.isEmpty(container.getSelectedItemStyleClass())) { listItemCssClass = container.getSelectedItemStyleClass(); anchorCssClass = container.getSelectedItemStyleClass(); } if (anyChildren && selected && anyChildSelected(entry, selectedSet) && !Strings.isEmpty(container.getItemWithSelectedChildStyleClass())) { listItemCssClass = container.getItemWithSelectedChildStyleClass(); } if (!Strings.isEmpty(entry.getCssClass())) { if (!Strings.isEmpty(listItemCssClass)) { listItemCssClass += " "; } listItemCssClass += entry.getCssClass(); } response.write("\n<li"); if (!Strings.isEmpty(listItemCssClass)) { response.write(" class=\""); response.write(listItemCssClass); response.write("\""); } response.write(">"); final String url = getUrl(entry); response.write("<a"); if (!Strings.isEmpty(anchorCssClass)) { response.write("class=\""); response.write(anchorCssClass); response.write("\""); } response.write(" href=\""); response.write(url); response.write("\"><span>"); // TODO. escape or not (probably a property would be nice? response.write(entry.getTitle()); response.write("</span></a>"); } // only decrement skip levels for child if current is begger than 0 int childSkipLevels = skipLevels - 1; // only decrement render levels when we are already rendering int childRenderLevels = skipLevels <= 0 ? renderLevels - 1 : renderLevels; if (anyChildren) { renderEntry(container, entry, response, selectedSet, childSkipLevels, childRenderLevels); } if (skipLevels == 0) { response.write("</li>\n"); } }
private void renderChild(MenuContainer container, ChildEntry entry, Response response, Set<ChildEntry> selectedSet, int skipLevels, int renderLevels) { boolean selected = selectedSet.contains(entry); boolean anyChildren = selected && anyChildren(entry); if (skipLevels <= 0) { String listItemCssClass = ""; String anchorCssClass = ""; if (selected && !Strings.isEmpty(container.getSelectedItemStyleClass())) { listItemCssClass = container.getSelectedItemStyleClass(); anchorCssClass = container.getSelectedItemStyleClass(); } if (anyChildren && selected && anyChildSelected(entry, selectedSet) && !Strings.isEmpty(container.getItemWithSelectedChildStyleClass())) { listItemCssClass = container.getItemWithSelectedChildStyleClass(); } if (!Strings.isEmpty(entry.getCssClass())) { if (!Strings.isEmpty(listItemCssClass)) { listItemCssClass += " "; } listItemCssClass += entry.getCssClass(); } response.write("\n<li"); if (!Strings.isEmpty(listItemCssClass)) { response.write(" class=\""); response.write(listItemCssClass); response.write("\""); } response.write(">"); final String url = getUrl(entry); response.write("<a"); if (!Strings.isEmpty(anchorCssClass)) { response.write(" class=\""); response.write(anchorCssClass); response.write("\""); } response.write(" href=\""); response.write(url); response.write("\"><span>"); // TODO. escape or not (probably a property would be nice? response.write(entry.getTitle()); response.write("</span></a>"); } // only decrement skip levels for child if current is begger than 0 int childSkipLevels = skipLevels - 1; // only decrement render levels when we are already rendering int childRenderLevels = skipLevels <= 0 ? renderLevels - 1 : renderLevels; if (anyChildren) { renderEntry(container, entry, response, selectedSet, childSkipLevels, childRenderLevels); } if (skipLevels == 0) { response.write("</li>\n"); } }
diff --git a/src/org/apache/xerces/validators/schema/TraverseSchema.java b/src/org/apache/xerces/validators/schema/TraverseSchema.java index 75864c882..e791fa12e 100644 --- a/src/org/apache/xerces/validators/schema/TraverseSchema.java +++ b/src/org/apache/xerces/validators/schema/TraverseSchema.java @@ -1,4504 +1,4504 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.validators.schema; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.validators.common.Grammar; import org.apache.xerces.validators.common.GrammarResolver; import org.apache.xerces.validators.common.GrammarResolverImpl; import org.apache.xerces.validators.common.XMLElementDecl; import org.apache.xerces.validators.common.XMLAttributeDecl; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.XUtil; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.utils.StringPool; import org.w3c.dom.Element; //REVISIT: for now, import everything in the DOM package import org.w3c.dom.*; import java.util.*; import java.net.URL; import java.net.MalformedURLException; //Unit Test import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.validators.common.XMLValidator; import org.apache.xerces.validators.datatype.DatatypeValidator.*; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.framework.XMLParser; import org.apache.xerces.framework.XMLDocumentScanner; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import java.io.IOException; import org.w3c.dom.Document; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.apache.xerces.validators.schema.SchemaSymbols; /** * Instances of this class get delegated to Traverse the Schema and * to populate the Grammar internal representation by * instances of Grammar objects. * Traverse a Schema Grammar: * As of April 07, 2000 the following is the * XML Representation of Schemas and Schema components, * Chapter 4 of W3C Working Draft. * <schema * attributeFormDefault = qualified | unqualified * blockDefault = #all or (possibly empty) subset of {equivClass, extension, restriction} * elementFormDefault = qualified | unqualified * finalDefault = #all or (possibly empty) subset of {extension, restriction} * id = ID * targetNamespace = uriReference * version = string> * Content: ((include | import | annotation)* , ((simpleType | complexType | element | group | attribute | attributeGroup | notation) , annotation*)+) * </schema> * * * <attribute * form = qualified | unqualified * id = ID * name = NCName * ref = QName * type = QName * use = default | fixed | optional | prohibited | required * value = string> * Content: (annotation? , simpleType?) * </> * * <element * abstract = boolean * block = #all or (possibly empty) subset of {equivClass, extension, restriction} * default = string * equivClass = QName * final = #all or (possibly empty) subset of {extension, restriction} * fixed = string * form = qualified | unqualified * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * nullable = boolean * ref = QName * type = QName> * Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*) * </> * * * <complexType * abstract = boolean * base = QName * block = #all or (possibly empty) subset of {extension, restriction} * content = elementOnly | empty | mixed | textOnly * derivedBy = extension | restriction * final = #all or (possibly empty) subset of {extension, restriction} * id = ID * name = NCName> * Content: (annotation? , (((minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern)* | (element | group | all | choice | sequence | any)*) , ((attribute | attributeGroup)* , anyAttribute?))) * </> * * * <attributeGroup * id = ID * name = NCName * ref = QName> * Content: (annotation?, (attribute|attributeGroup), anyAttribute?) * </> * * <anyAttribute * id = ID * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}> * Content: (annotation?) * </anyAttribute> * * <group * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * ref = QName> * Content: (annotation? , (element | group | all | choice | sequence | any)*) * </> * * <all * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </all> * * <choice * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </choice> * * <sequence * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </sequence> * * * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace} * processContents = lax | skip | strict> * Content: (annotation?) * </any> * * <unique * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </unique> * * <key * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </key> * * <keyref * id = ID * name = NCName * refer = QName> * Content: (annotation? , (selector , field+)) * </keyref> * * <selector> * Content: XPathExprApprox : An XPath expression * </selector> * * <field> * Content: XPathExprApprox : An XPath expression * </field> * * * <notation * id = ID * name = NCName * public = A public identifier, per ISO 8879 * system = uriReference> * Content: (annotation?) * </notation> * * <annotation> * Content: (appinfo | documentation)* * </annotation> * * <include * id = ID * schemaLocation = uriReference> * Content: (annotation?) * </include> * * <import * id = ID * namespace = uriReference * schemaLocation = uriReference> * Content: (annotation?) * </import> * * <simpleType * abstract = boolean * base = QName * derivedBy = | list | restriction : restriction * id = ID * name = NCName> * Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* ) * </simpleType> * * <length * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </length> * * <minLength * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </minLength> * * <maxLength * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </maxLength> * * * <pattern * id = ID * value = string> * Content: ( annotation? ) * </pattern> * * * <enumeration * id = ID * value = string> * Content: ( annotation? ) * </enumeration> * * <maxInclusive * id = ID * value = string> * Content: ( annotation? ) * </maxInclusive> * * <maxExclusive * id = ID * value = string> * Content: ( annotation? ) * </maxExclusive> * * <minInclusive * id = ID * value = string> * Content: ( annotation? ) * </minInclusive> * * * <minExclusive * id = ID * value = string> * Content: ( annotation? ) * </minExclusive> * * <precision * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </precision> * * <scale * id = ID * value = nonNegativeInteger> * Content: ( annotation? ) * </scale> * * <encoding * id = ID * value = | hex | base64 > * Content: ( annotation? ) * </encoding> * * * <duration * id = ID * value = timeDuration> * Content: ( annotation? ) * </duration> * * <period * id = ID * value = timeDuration> * Content: ( annotation? ) * </period> * * * @author Eric Ye, Jeffrey Rodriguez, Andy Clark * * @see org.apache.xerces.validators.common.Grammar * * @version $Id$ */ public class TraverseSchema implements NamespacesScope.NamespacesHandler{ //CONSTANTS private static final int TOP_LEVEL_SCOPE = -1; //debuggin private static boolean DEBUGGING = false; //private data members private XMLErrorReporter fErrorReporter = null; private StringPool fStringPool = null; private GrammarResolver fGrammarResolver = null; private SchemaGrammar fSchemaGrammar = null; private Element fSchemaRootElement; private DatatypeValidatorFactoryImpl fDatatypeRegistry = DatatypeValidatorFactoryImpl.getDatatypeRegistry(); private Hashtable fComplexTypeRegistry = new Hashtable(); private Hashtable fAttributeDeclRegistry = new Hashtable(); private Vector fIncludeLocations = new Vector(); private Vector fImportLocations = new Vector(); private int fAnonTypeCount =0; private int fScopeCount=0; private int fCurrentScope=TOP_LEVEL_SCOPE; private int fSimpleTypeAnonCount = 0; private Stack fCurrentTypeNameStack = new Stack(); private Hashtable fElementRecurseComplex = new Hashtable(); private boolean fElementDefaultQualified = false; private boolean fAttributeDefaultQualified = false; private int fTargetNSURI; private String fTargetNSURIString = ""; private NamespacesScope fNamespacesScope = null; private String fCurrentSchemaURL = ""; private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); // REVISIT: maybe need to be moved into SchemaGrammar class public class ComplexTypeInfo { public String typeName; public DatatypeValidator baseDataTypeValidator; public ComplexTypeInfo baseComplexTypeInfo; public int derivedBy = 0; public int blockSet = 0; public int finalSet = 0; public boolean isAbstract = false; public int scopeDefined = -1; public int contentType; public int contentSpecHandle = -1; public int templateElementIndex = -1; public int attlistHead = -1; public DatatypeValidator datatypeValidator; } //REVISIT: verify the URI. public final static String SchemaForSchemaURI = "http://www.w3.org/TR-1/Schema"; private TraverseSchema( ) { // new TraverseSchema() is forbidden; } public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } public void startNamespaceDeclScope(int prefix, int uri){ //TO DO } public void endNamespaceDeclScope(int prefix){ //TO DO, do we need to do anything here? } private String resolvePrefixToURI (String prefix) throws Exception { String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix))); if (uriStr == null) { // REVISIT: Localize reportGenericSchemaError("prefix : [" + prefix +"] can not be resolved to a URI"); return ""; } //REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype. if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && fTargetNSURIString.length() == 0) { uriStr = ""; } return uriStr; } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver, XMLErrorReporter errorReporter, String schemaURL ) throws Exception { fErrorReporter = errorReporter; fCurrentSchemaURL = schemaURL; doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver ) throws Exception { doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public void doTraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver) throws Exception { fNamespacesScope = new NamespacesScope(this); fSchemaRootElement = root; fStringPool = stringPool; fSchemaGrammar = schemaGrammar; fGrammarResolver = grammarResolver; if (root == null) { // REVISIT: Anything to do? return; } //Make sure namespace binding is defaulted String rootPrefix = root.getPrefix(); if( rootPrefix == null || rootPrefix.length() == 0 ){ String xmlns = root.getAttribute("xmlns"); if( xmlns.length() == 0 ) root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA ); } //Retrieve the targetnamespace URI information fTargetNSURIString = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (fTargetNSURIString==null) { fTargetNSURIString=""; } fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString); if (fGrammarResolver == null) { // REVISIT: Localize reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema"); } else{ fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry); fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry); fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry); fSchemaGrammar.setNamespacesScope(fNamespacesScope); fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString); fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar); } // Retrived the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; checkTopLevelDuplicateNames(root); //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { //traverseAttributeGroupDecl(child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { traverseAttributeDecl( child, null ); } else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) { traverseWildcardDecl( child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { //traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { ; //TO DO } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { traverseInclude(child); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } } // for each child node } // traverseSchema(Element) private void checkTopLevelDuplicateNames(Element root) { //TO DO : !!! } private void extractTopLevel3Components(Element root){ for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fSchemaGrammar.topLevelAttrGrpDecls.put(name, child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { fSchemaGrammar.topLevelAttrDecls.put(name, child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { fSchemaGrammar.topLevelGroupDecls.put(name, child); } } // for each child node } /** * Expands a system id and returns the system id as a URL, if * it can be expanded. A return value of null means that the * identifier is already expanded. An exception thrown * indicates a failure to expand the id. * * @param systemId The systemId to be expanded. * * @return Returns the URL object representing the expanded system * identifier. A null value indicates that the given * system identifier is already expanded. * */ private String expandSystemId(String systemId, String currentSystemId) throws Exception{ String id = systemId; // check for bad parameters id if (id == null || id.length() == 0) { return systemId; } // if id already expanded, return try { URL url = new URL(id); if (url != null) { return systemId; } } catch (MalformedURLException e) { // continue on... } // normalize id id = fixURI(id); // normalize base URL base = null; URL url = null; try { if (currentSystemId == null) { String dir; try { dir = fixURI(System.getProperty("user.dir")); } catch (SecurityException se) { dir = ""; } if (!dir.endsWith("/")) { dir = dir + "/"; } base = new URL("file", "", dir); } else { base = new URL(currentSystemId); } // expand id url = new URL(base, id); } catch (Exception e) { // let it go through } if (url == null) { return systemId; } return url.toString(); } /** * Fixes a platform dependent filename to standard URI form. * * @param str The string to fix. * * @return Returns the fixed URI string. */ private static String fixURI(String str) { // handle platform dependent strings str = str.replace(java.io.File.separatorChar, '/'); // Windows fix if (str.length() >= 2) { char ch1 = str.charAt(1); if (ch1 == ':') { char ch0 = Character.toUpperCase(str.charAt(0)); if (ch0 >= 'A' && ch0 <= 'Z') { str = "/" + str; } } } // done return str; } private void traverseInclude(Element includeDecl) throws Exception { //TO DO: !!!!! location needs to be resolved first. String location = includeDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION); location = expandSystemId(location, fCurrentSchemaURL); if (fIncludeLocations.contains((Object)location)) { return; } fIncludeLocations.addElement((Object)location); DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( location); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { //e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) { // REVISIT: Localize reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"'"); } else { boolean saveElementDefaultQualified = fElementDefaultQualified; boolean saveAttributeDefaultQualified = fAttributeDefaultQualified; int saveScope = fCurrentScope; String savedSchemaURL = fCurrentSchemaURL; Element saveRoot = fSchemaRootElement; fSchemaRootElement = root; fCurrentSchemaURL = location; traverseIncludedSchema(root); fCurrentSchemaURL = savedSchemaURL; fCurrentScope = saveScope; fElementDefaultQualified = saveElementDefaultQualified; fAttributeDefaultQualified = saveAttributeDefaultQualified; fSchemaRootElement = saveRoot; } } } private void traverseIncludedSchema(Element root) throws Exception { // Retrived the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; checkTopLevelDuplicateNames(root); //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getNodeName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { //traverseAttributeGroupDecl(child); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { traverseAttributeDecl( child, null ); } else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) { traverseWildcardDecl( child); } else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) { //traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { ; //TO DO } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { traverseInclude(child); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } } // for each child node } private void traverseImport(Element importDecl) throws Exception { String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION); location = expandSystemId(location, fCurrentSchemaURL); String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE); SchemaGrammar importedGrammar = new SchemaGrammar(); if (fGrammarResolver.getGrammar(namespaceString) != null) { importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString); } if (fImportLocations.contains((Object)location)) { return; } fImportLocations.addElement((Object)location); DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( location); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE); if (!targetNSURI.equals(namespaceString) ) { // REVISIT: Localize reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"' from what is declared '"+namespaceString+"'."); } else new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location); } else { reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location); } } /** * No-op - Traverse Annotation Declaration * * @param comment */ private void traverseAnnotationDecl(Element comment) { //TO DO return ; } /** * Traverse SimpleType declaration: * <simpleType * abstract = boolean * base = QName * derivedBy = | list | restriction : restriction * id = ID * name = NCName> * Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* ) * </simpleType> * * @param simpleTypeDecl * @return */ private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception { String varietyProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); if (varietyProperty.length() == 0) { varietyProperty = SchemaSymbols.ATTVAL_RESTRICTION; } String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME ); String baseTypeQNameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ); String abstractProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); int newSimpleTypeName = -1; if ( nameProperty.equals("")) { // anonymous simpleType newSimpleTypeName = fStringPool.addSymbol( "#S#"+fSimpleTypeAnonCount++ ); //"http://www.apache.org/xml/xerces/internalDatatype"+fSimpleTypeAnonCount++ ); } else newSimpleTypeName = fStringPool.addSymbol( nameProperty ); int basetype; DatatypeValidator baseValidator = null; if( baseTypeQNameProperty!= null ) { basetype = fStringPool.addSymbol( baseTypeQNameProperty ); String prefix = ""; String localpart = baseTypeQNameProperty; int colonptr = baseTypeQNameProperty.indexOf(":"); if ( colonptr > 0) { prefix = baseTypeQNameProperty.substring(0,colonptr); localpart = baseTypeQNameProperty.substring(colonptr+1); } String uri = resolvePrefixToURI(prefix); baseValidator = getDatatypeValidator(uri, localpart); if (baseValidator == null) { Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { traverseSimpleTypeDecl( baseTypeNode ); baseValidator = getDatatypeValidator(uri, localpart); if (baseValidator == null) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ), simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME) }); return -1; //reportGenericSchemaError("Base type could not be found : " + baseTypeQNameProperty); } } else { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ), simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME) }); return -1; //reportGenericSchemaError("Base type could not be found : " + baseTypeQNameProperty); } } } // Any Children if so then check Content otherwise bail out Element content = XUtil.getFirstChildElement( simpleTypeDecl ); int numFacets = 0; Hashtable facetData = null; if( content != null ) { //Content follows: ( annotation? , facets* ) //annotation ? ( 0 or 1 ) if( content.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( content ); content = XUtil.getNextSiblingElement(content); } //TODO: If content is annotation again should raise validation error // if( content.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) { // throw ValidationException(); } // //facets * ( 0 or more ) int numEnumerationLiterals = 0; facetData = new Hashtable(); Vector enumData = new Vector(); while (content != null) { if (content.getNodeType() == Node.ELEMENT_NODE) { Element facetElt = (Element) content; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; String enumVal = facetElt.getAttribute(SchemaSymbols.ATT_VALUE); enumData.addElement(enumVal); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( content ); } //TODO: If enumContent is encounter again should raise validation error // enumContent.getNextSibling(); // if( enumContent.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) { // throw ValidationException(); } // } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } //content = (Element) content.getNextSibling(); content = XUtil.getNextSiblingElement(content); } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } } // create & register validator for "generated" type if it doesn't exist String nameOfType = fStringPool.toString( newSimpleTypeName); if (fTargetNSURIString.length () != 0) { nameOfType = fTargetNSURIString+","+nameOfType; } try { DatatypeValidator newValidator = fDatatypeRegistry.getDatatypeValidator( nameOfType ); if( newValidator == null ) { // not previously registered boolean derivedByList = varietyProperty.equals( SchemaSymbols.ATTVAL_LIST ) ? true:false; fDatatypeRegistry.createDatatypeValidator( nameOfType, baseValidator, facetData, derivedByList ); } } catch (Exception e) { //e.printStackTrace(System.err); reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() }); } return fStringPool.addSymbol(nameOfType); } /* * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace} * processContents = lax | skip | strict> * Content: (annotation?) * </any> */ private int traverseAny(Element child) throws Exception { int anyIndex = -1; String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim(); String processContents = child.getAttribute("processContents").trim(); int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY; int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER; int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL; if (processContents.length() > 0 && !processContents.equals("strict")) { if (processContents.equals("lax")) { processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX; processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX; processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX; } else if (processContents.equals("skip")) { processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP; processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP; processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP; } } if (namespace.length() == 0 || namespace.equals("##any")) { anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, -1, false); } else if (namespace.equals("##other")) { String uri = child.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace"); int uriIndex = fStringPool.addSymbol(uri); anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false); } else if (namespace.equals("##local")) { anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, -1, false); } else if (namespace.length() > 0) { StringTokenizer tokenizer = new StringTokenizer(namespace); Vector tokens = new Vector(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals("##targetNamespace")) { token = child.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace"); } tokens.addElement(token); } String uri = (String)tokens.elementAt(0); int uriIndex = fStringPool.addSymbol(uri); int leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false); int valueIndex = leafIndex; int count = tokens.size(); if (count > 1) { uri = (String)tokens.elementAt(1); uriIndex = fStringPool.addSymbol(uri); leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false); int otherValueIndex = leafIndex; int choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, valueIndex, otherValueIndex, false); for (int i = 2; i < count; i++) { uri = (String)tokens.elementAt(i); uriIndex = fStringPool.addSymbol(uri); leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false); otherValueIndex = leafIndex; choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, otherValueIndex, false); } anyIndex = choiceIndex; } else { anyIndex = leafIndex; } } else { // REVISIT: Localize reportGenericSchemaError("Empty namespace attribute for any element"); } return anyIndex; } public DatatypeValidator getDatatypeValidator(String uri, String localpart) { DatatypeValidator dv = null; if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { dv = fDatatypeRegistry.getDatatypeValidator( localpart ); } else { dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart ); } return dv; } /* * <anyAttribute * id = ID * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}> * Content: (annotation?) * </anyAttribute> */ private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception { XMLAttributeDecl anyAttDecl = new XMLAttributeDecl(); String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim(); String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim(); String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace"); if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) { anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY; } else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) { anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER; anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri); } else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) { anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LOCAL; } else if (namespace.length() > 0){ anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST; StringTokenizer tokenizer = new StringTokenizer(namespace); int aStringList = fStringPool.startStringList(); Vector tokens = new Vector(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals("##targetNamespace")) { token = curTargetUri; } if (!fStringPool.addStringToList(aStringList, fStringPool.addSymbol(token))){ reportGenericSchemaError("Internal StringPool error when reading the "+ "namespace attribute for anyattribute declaration"); } } fStringPool.finishStringList(aStringList); anyAttDecl.enumeration = aStringList; } else { // REVISIT: Localize reportGenericSchemaError("Empty namespace attribute for anyattribute declaration"); } // default processContents is "strict"; anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_STRICT; if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){ anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_SKIP; } else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) { anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_LAX; } return anyAttDecl; } private XMLAttributeDecl mergeTwoAnyAttribute(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) { if (oneAny.type == -1) { return oneAny; } if (anotherAny.type == -1) { return anotherAny; } if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return anotherAny; } if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return oneAny; } if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { if ( anotherAny.name.uri == oneAny.name.uri ) { return oneAny; } else { oneAny.type = -1; return oneAny; } } else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) { return anotherAny; } else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { if (!fStringPool.stringInList(anotherAny.enumeration, oneAny.name.uri) ) { return anotherAny; } else { int[] anotherAnyURIs = fStringPool.stringListAsIntArray(anotherAny.enumeration); int newList = fStringPool.startStringList(); for (int i=0; i< anotherAnyURIs.length; i++) { if (anotherAnyURIs[i] != oneAny.name.uri ) { fStringPool.addStringToList(newList, anotherAnyURIs[i]); } } fStringPool.finishStringList(newList); anotherAny.enumeration = newList; return anotherAny; } } } if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) { if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER || anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) { return oneAny; } else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { oneAny.type = -1; return oneAny; } } if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER){ if (!fStringPool.stringInList(oneAny.enumeration, anotherAny.name.uri) ) { return oneAny; } else { int[] oneAnyURIs = fStringPool.stringListAsIntArray(oneAny.enumeration); int newList = fStringPool.startStringList(); for (int i=0; i< oneAnyURIs.length; i++) { if (oneAnyURIs[i] != anotherAny.name.uri ) { fStringPool.addStringToList(newList, oneAnyURIs[i]); } } fStringPool.finishStringList(newList); oneAny.enumeration = newList; return oneAny; } } else if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) { oneAny.type = -1; return oneAny; } else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { int[] result = intersect2sets( fStringPool.stringListAsIntArray(oneAny.enumeration), fStringPool.stringListAsIntArray(anotherAny.enumeration)); int newList = fStringPool.startStringList(); for (int i=0; i<result.length; i++) { fStringPool.addStringToList(newList, result[i]); } fStringPool.finishStringList(newList); oneAny.enumeration = newList; return oneAny; } } // should never go there; return oneAny; } int[] intersect2sets(int[] one, int[] theOther){ int[] result = new int[(one.length>theOther.length?one.length:theOther.length)]; // simple implemention, int count = 0; for (int i=0; i<one.length; i++) { for(int j=0; j<theOther.length; j++) { if (one[i]==theOther[j]) { result[count++] = one[i]; } } } int[] result2 = new int[count]; System.arraycopy(result, 0, result2, 0, count); return result2; } /** * Traverse ComplexType Declaration. * * <complexType * abstract = boolean * base = QName * block = #all or (possibly empty) subset of {extension, restriction} * content = elementOnly | empty | mixed | textOnly * derivedBy = extension | restriction * final = #all or (possibly empty) subset of {extension, restriction} * id = ID * name = NCName> * Content: (annotation? , (((minExclusive | minInclusive | maxExclusive * | maxInclusive | precision | scale | length | minLength * | maxLength | encoding | period | duration | enumeration * | pattern)* | (element | group | all | choice | sequence | any)*) , * ((attribute | attributeGroup)* , anyAttribute?))) * </complexType> * @param complexTypeDecl * @return */ //REVISIT: TO DO, base and derivation ??? private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception { String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE); String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK ); String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT); String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL ); String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID ); String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME); boolean isNamedType = false; if ( DEBUGGING ) System.out.println("traversing complex Type : " + typeName +","+base+","+content+"."); if (typeName.equals("")) { // gensym a unique name //typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++; typeName = "#"+fAnonTypeCount++; } else { fCurrentTypeNameStack.push(typeName); isNamedType = true; } if (isTopLevel(complexTypeDecl)) { String fullName = fTargetNSURIString+","+typeName; ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName); if (temp != null ) { return fStringPool.addSymbol(fullName); } } int scopeDefined = fScopeCount++; int previousScope = fCurrentScope; fCurrentScope = scopeDefined; Element child = null; int contentSpecType = -1; int csnType = 0; int left = -2; int right = -2; ComplexTypeInfo baseTypeInfo = null; //if base is a complexType; DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType DatatypeValidator simpleTypeValidator = null; int baseTypeSymbol = -1; String fullBaseName = ""; boolean baseIsSimpleSimple = false; boolean baseIsComplexSimple = false; boolean derivedByRestriction = true; boolean derivedByExtension = false; int baseContentSpecHandle = -1; Element baseTypeNode = null; //int parsedderivedBy = parseComplexDerivedBy(derivedBy); //handle the inhreitance here. if (base.length()>0) { //first check if derivedBy is present if (derivedBy.length() == 0) { // REVISIT: Localize reportGenericSchemaError("derivedBy must be present when base is present in " +SchemaSymbols.ELT_COMPLEXTYPE +" "+ typeName); } else { if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) { derivedByRestriction = false; } String prefix = ""; String localpart = base; int colonptr = base.indexOf(":"); if ( colonptr > 0) { prefix = base.substring(0,colonptr); localpart = base.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String typeURI = resolvePrefixToURI(prefix); // check if the base type is from the same Schema; if ( ! typeURI.equals(fTargetNSURIString) && ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{ baseTypeInfo = getTypeInfoFromNS(typeURI, localpart); if (baseTypeInfo == null) { baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart); if (baseTypeValidator == null) { //TO DO: report error here; System.out.println("Could not find base type " +localpart + " in schema " + typeURI); } else{ baseIsSimpleSimple = true; } } } else { fullBaseName = typeURI+","+localpart; // assume the base is a complexType and try to locate the base type first baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName); // if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet; // 2: base is SimpleTYpe; if (baseTypeInfo == null) { baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (baseTypeValidator == null) { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode ); baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName; } else { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode ); simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (simpleTypeValidator == null) { //TO DO: signal error here. } baseIsSimpleSimple = true; } else { // REVISIT: Localize reportGenericSchemaError("Base type could not be found : " + base); } } } else { simpleTypeValidator = baseTypeValidator; baseIsSimpleSimple = true; } } } //Schema Spec : 5.11: Complex Type Definition Properties Correct : 2 if (baseIsSimpleSimple && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName); } //if the base is a complexType if (baseTypeInfo != null ) { //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 // 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1 if (derivedByRestriction) { //REVISIT: check base Type's finalset does not include "restriction" } else { //REVISIT: check base Type's finalset doest not include "extension" } if ( baseTypeInfo.contentSpecHandle > -1) { if (derivedByRestriction) { //REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10 checkParticleDerivationOK(complexTypeDecl, baseTypeNode); } baseContentSpecHandle = baseTypeInfo.contentSpecHandle; } else if ( baseTypeInfo.datatypeValidator != null ) { baseTypeValidator = baseTypeInfo.datatypeValidator; baseIsComplexSimple = true; } } //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 if (baseIsComplexSimple && !derivedByRestriction ) { // REVISIT: Localize reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName); } } // END of if (derivedBy.length() == 0) {} else {} } // END of if (base.length() > 0) {} // skip refinement and annotations child = null; if (baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; int numEnumerationLiterals = 0; int numFacets = 0; Hashtable facetData = new Hashtable(); Vector enumData = new Vector(); //REVISIT: there is a better way to do this, for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) || child.getNodeName().equals(SchemaSymbols.ELT_SCALE) || child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) || child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) || child.getNodeName().equals(SchemaSymbols.ELT_DURATION) || child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) || child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) || child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)); child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeType() == Node.ELEMENT_NODE ) { Element facetElt = (Element) child; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE)); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( child ); } // TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } //if (numFacets > 0) // baseTypeValidator.setFacets(facetData, derivedBy ); if (numFacets > 0) { simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator, facetData, false ); } else simpleTypeValidator = baseTypeValidator; if (child != null) { // REVISIT: Localize reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName + "', because it restricts another complexSimpleType"); } } // if content = textonly, base is a datatype if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { //TO DO if (base.length() == 0) { simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); } else if ( baseTypeValidator == null && baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype reportSchemaError(SchemaMessageProvider.NotADatatype, new Object [] { base }); //REVISIT check forward refs //handle datatypes contentSpecType = XMLElementDecl.TYPE_SIMPLE; /**** left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, fStringPool.addSymbol(base), -1, false); /****/ } else { if (!baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_CHILDREN; } csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; boolean mixedContent = false; //REVISIT: is the default content " elementOnly" boolean elementContent = true; boolean textContent = false; boolean emptyContent = false; left = -2; right = -2; boolean hadContent = false; if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) { contentSpecType = XMLElementDecl.TYPE_EMPTY; emptyContent = true; elementContent = false; left = -1; // no contentSpecNode needed } else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) { contentSpecType = XMLElementDecl.TYPE_MIXED; mixedContent = true; elementContent = false; csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) { elementContent = true; } else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { textContent = true; elementContent = false; } if (mixedContent) { // add #PCDATA leaf left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, -1, // -1 means "#PCDATA" is name -1, false); csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } boolean seeParticle = false; boolean seeOtherParticle = false; boolean seeAll = false; for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; // to save the particle's contentSpec handle hadContent = true; seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { if (mixedContent || elementContent) { if ( DEBUGGING ) System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME)); QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; seeOtherParticle = true; } else { reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null); } } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); seeParticle = true; seeAll = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) || childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { break; // attr processing is done later on in this method } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) { //REVISIT, do nothing for annotation for now. } else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) { break; //REVISIT, do nothing for attribute wildcard for now. } else { // datatype qual if (!baseIsComplexSimple ) if (base.equals("")) reportSchemaError(SchemaMessageProvider.GenericError, - new Object [] { "unrecogized child '"+childName+"' in compelx type "+typeName }); + new Object [] { "unrecognized child '"+childName+"' in complex type "+typeName }); else reportSchemaError(SchemaMessageProvider.GenericError, - new Object [] { "unrecogized child '"+childName+"' in compelx type '"+typeName+"' with base "+base }); + new Object [] { "unrecognized child '"+childName+"' in complex type '"+typeName+"' with base "+base }); } // if base is complextype with simpleType content, can't have any particle children at all. if (baseIsComplexSimple && seeParticle) { // REVISIT: Localize - reportGenericSchemaError("In complexType "+typeName+", base type is complextype with simpleType content, can't have any particle children at all"); + reportGenericSchemaError("In complexType "+typeName+", base type is complexType with simpleType content, can't have any particle children at all"); hadContent = false; left = index = -2; contentSpecType = XMLElementDecl.TYPE_SIMPLE; break; } // check the minOccurs and maxOccurs of the particle, and fix the // contentspec accordingly if (seeParticle) { index = expandContentModel(index, child); } //end of if (seeParticle) if (seeAll && seeOtherParticle) { // REVISIT: Localize reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName); } if (seeAll) { //TO DO: REVISIT //check the minOccurs = 1 and maxOccurs = 1 } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } //end looping through the children if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent) && (base.length() == 0 || ( base.length() > 0 && derivedByRestriction && !baseIsComplexSimple)) ) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); // REVISIT: Localize reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content " +"need to have at least one particle child"); } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); if (mixedContent && hadContent) { // set occurrence count left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, left, -1, false); } } // if derived by extension and base complextype has a content model, // compose the final content model by concatenating the base and the // current in sequence. if (!derivedByRestriction && baseContentSpecHandle > -1 ) { if (left == -2) { left = baseContentSpecHandle; } else left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, baseContentSpecHandle, left, false); } // REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType> if (content.length() == 0 && base.length() == 0 && left == -2) { contentSpecType = XMLElementDecl.TYPE_ANY; } if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) { if (base.length() > 0 && baseTypeInfo != null && baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) { contentSpecType = XMLElementDecl.TYPE_EMPTY; } } if ( DEBUGGING ) System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", " + baseContentSpecHandle +", " + left +", "+scopeDefined); ComplexTypeInfo typeInfo = new ComplexTypeInfo(); typeInfo.baseComplexTypeInfo = baseTypeInfo; typeInfo.baseDataTypeValidator = baseTypeValidator; int derivedByInt = -1; if (derivedBy.length() > 0) { derivedByInt = parseComplexDerivedBy(derivedBy); } typeInfo.derivedBy = derivedByInt; typeInfo.scopeDefined = scopeDefined; typeInfo.contentSpecHandle = left; typeInfo.contentType = contentSpecType; typeInfo.datatypeValidator = simpleTypeValidator; typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK)); typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL)); typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ; //add a template element to the grammar element decl pool. int typeNameIndex = fStringPool.addSymbol(typeName); int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined, contentSpecType, left, -1, simpleTypeValidator); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); // (attribute | attrGroupRef)* XMLAttributeDecl attWildcard = null; Vector anyAttDecls = new Vector(); for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+ ", base type has simpleType "+ "content and derivation method is"+ " 'restriction', can't have any "+ "attribute children at all"); break; } traverseAttributeDecl(child, typeInfo); } else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+", base "+ "type has simpleType content and "+ "derivation method is 'restriction',"+ " can't have any attribute children at all"); break; } traverseAttributeGroupDecl(child,typeInfo,anyAttDecls); } else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { attWildcard = traverseAnyAttribute(child); } } if (attWildcard != null) { XMLAttributeDecl fromGroup = null; final int count = anyAttDecls.size(); if ( count > 0) { fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0); for (int i=1; i<count; i++) { fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i)); } } if (fromGroup != null) { int saveProcessContents = attWildcard.defaultType; attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup); attWildcard.defaultType = saveProcessContents; } } else { //REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case } // merge in base type's attribute decls XMLAttributeDecl baseAttWildcard = null; if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) { int attDefIndex = baseTypeInfo.attlistHead; while ( attDefIndex > -1 ) { fTempAttributeDecl.clear(); fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl); if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) { if (attWildcard == null) { baseAttWildcard = fTempAttributeDecl; } attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } // if found a duplicate, if it is derived by restriction. then skip the one from the base type /**/ int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name); if ( temp > -1) { if (derivedByRestriction) { attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } } /**/ fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, fTempAttributeDecl.name, fTempAttributeDecl.type, fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType, fTempAttributeDecl.defaultValue, fTempAttributeDecl.datatypeValidator, fTempAttributeDecl.list); attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); } } // att wildcard will inserted after all attributes were processed if (attWildcard != null) { if (attWildcard.type != -1) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attWildcard.name, attWildcard.type, attWildcard.enumeration, attWildcard.defaultType, attWildcard.defaultValue, attWildcard.datatypeValidator, attWildcard.list); } else { //REVISIT: unclear in Schema spec if should report error here. } } else if (baseAttWildcard != null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, baseAttWildcard.name, baseAttWildcard.type, baseAttWildcard.enumeration, baseAttWildcard.defaultType, baseAttWildcard.defaultValue, baseAttWildcard.datatypeValidator, baseAttWildcard.list); } typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); if (!typeName.startsWith("#")) { typeName = fTargetNSURIString + "," + typeName; } typeInfo.typeName = new String(typeName); if ( DEBUGGING ) System.out.println("add complex Type to Registry: " + typeName +","+content+"."); fComplexTypeRegistry.put(typeName,typeInfo); // before exit the complex type definition, restore the scope, mainly for nested Anonymous Types fCurrentScope = previousScope; if (isNamedType) { fCurrentTypeNameStack.pop(); checkRecursingComplexType(); } //set template element's typeInfo fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo); typeNameIndex = fStringPool.addSymbol(typeName); return typeNameIndex; } // end of method: traverseComplexTypeDecl private void checkRecursingComplexType() throws Exception { if ( fCurrentTypeNameStack.empty() ) { if (! fElementRecurseComplex.isEmpty() ) { Enumeration e = fElementRecurseComplex.keys(); while( e.hasMoreElements() ) { QName nameThenScope = (QName) e.nextElement(); String typeName = (String) fElementRecurseComplex.get(nameThenScope); int eltUriIndex = nameThenScope.uri; int eltNameIndex = nameThenScope.localpart; int enclosingScope = nameThenScope.prefix; ComplexTypeInfo typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName); if (typeInfo==null) { throw new Exception ( "Internal Error in void checkRecursingComplexType(). " ); } else { int elementIndex = fSchemaGrammar.addElementDecl(new QName(-1, eltNameIndex, eltNameIndex, eltUriIndex), enclosingScope, typeInfo.scopeDefined, typeInfo.contentType, typeInfo.contentSpecHandle, typeInfo.attlistHead, typeInfo.datatypeValidator); fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); } } fElementRecurseComplex.clear(); } } } private void checkParticleDerivationOK(Element derivedTypeNode, Element baseTypeNode) { //TO DO: !!! } private int expandContentModel ( int index, Element particle) throws Exception { String minOccurs = particle.getAttribute(SchemaSymbols.ATT_MINOCCURS); String maxOccurs = particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS); int min=1, max=1; if (minOccurs.equals("")) { minOccurs = "1"; } if (maxOccurs.equals("") ){ if ( minOccurs.equals("0")) { maxOccurs = "1"; } else { maxOccurs = minOccurs; } } int leafIndex = index; //REVISIT: !!! minoccurs, maxoccurs. if (minOccurs.equals("1")&& maxOccurs.equals("1")) { } else if (minOccurs.equals("0")&& maxOccurs.equals("1")) { //zero or one index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, index, -1, false); } else if (minOccurs.equals("0")&& maxOccurs.equals("unbounded")) { //zero or more index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, index, -1, false); } else if (minOccurs.equals("1")&& maxOccurs.equals("unbounded")) { //one or more index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, index, -1, false); } else if (maxOccurs.equals("unbounded") ) { // >=2 or more try { min = Integer.parseInt(minOccurs); } catch (Exception e) { reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "illegal value for minOccurs : '" +e.getMessage()+ "' " }); } if (min<2) { //REVISIT: report Error here } // => a,a,..,a+ index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, index, -1, false); for (int i=0; i < (min-1); i++) { index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, leafIndex, index, false); } } else { // {n,m} => a,a,a,...(a),(a),... try { min = Integer.parseInt(minOccurs); max = Integer.parseInt(maxOccurs); } catch (Exception e){ reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "}); } if (min==0) { int optional = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, leafIndex, -1, false); index = optional; for (int i=0; i < (max-min-1); i++) { index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, index, optional, false); } } else { for (int i=0; i<(min-1); i++) { index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, index, leafIndex, false); } int optional = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, leafIndex, -1, false); for (int i=0; i < (max-min); i++) { index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, index, optional, false); } } } return index; } /** * Traverses Schema attribute declaration. * * <attribute * form = qualified | unqualified * id = ID * name = NCName * ref = QName * type = QName * use = default | fixed | optional | prohibited | required * value = string> * Content: (annotation? , simpleType?) * <attribute/> * * @param attributeDecl * @return * @exception Exception */ private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo ) throws Exception { String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME); int attName = fStringPool.addSymbol(attNameStr);// attribute name String isQName = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute DatatypeValidator dv = null; // attribute type int attType = -1; boolean attIsList = false; int dataTypeSymbol = -1; String ref = attrDecl.getAttribute(SchemaSymbols.ATT_REF); String datatype = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE); String localpart = null; if (!ref.equals("")) { if (XUtil.getFirstChildElement(attrDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo); return -1; // TO DO // REVISIT: different NS, not supported yet. // REVISIT: Localize //reportGenericSchemaError("Feature not supported: see an attribute from different NS"); } Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart); if (referredAttribute != null) { traverseAttributeDecl(referredAttribute, typeInfo); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attribute " + ref); } return -1; } if (datatype.equals("")) { Element child = XUtil.getFirstChildElement(attrDecl); while (child != null && !child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE)) child = XUtil.getNextSiblingElement(child); if (child != null && child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE)) { attType = XMLAttributeDecl.TYPE_SIMPLE; dataTypeSymbol = traverseSimpleTypeDecl(child); localpart = fStringPool.toString(dataTypeSymbol); } else { attType = XMLAttributeDecl.TYPE_SIMPLE; localpart = "string"; dataTypeSymbol = fStringPool.addSymbol(localpart); } localpart = fStringPool.toString(dataTypeSymbol); dv = fDatatypeRegistry.getDatatypeValidator(localpart); } else { String prefix = ""; localpart = datatype; dataTypeSymbol = fStringPool.addSymbol(localpart); int colonptr = datatype.indexOf(":"); if ( colonptr > 0) { prefix = datatype.substring(0,colonptr); localpart = datatype.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) || typeURI.length()==0) { dv = getDatatypeValidator("", localpart); if (localpart.equals("ID")) { attType = XMLAttributeDecl.TYPE_ID; } else if (localpart.equals("IDREF")) { attType = XMLAttributeDecl.TYPE_IDREF; } else if (localpart.equals("IDREFS")) { attType = XMLAttributeDecl.TYPE_IDREF; attIsList = true; } else if (localpart.equals("ENTITY")) { attType = XMLAttributeDecl.TYPE_ENTITY; } else if (localpart.equals("ENTITIES")) { attType = XMLAttributeDecl.TYPE_ENTITY; attIsList = true; } else if (localpart.equals("NMTOKEN")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; } else if (localpart.equals("NMTOKENS")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; attIsList = true; } else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) { attType = XMLAttributeDecl.TYPE_NOTATION; } else { attType = XMLAttributeDecl.TYPE_SIMPLE; if (dv == null && typeURI.length() == 0) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); }else { // REVISIT: Localize reportGenericSchemaError("simpleType not found : " + localpart); } } } } else { // check if the type is from the same Schema dv = getDatatypeValidator(typeURI, localpart); if (dv == null && typeURI.equals(fTargetNSURIString) ) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); }else { // REVISIT: Localize reportGenericSchemaError("simpleType not found : " + localpart); } } attType = XMLAttributeDecl.TYPE_SIMPLE; } } // attribute default type int attDefaultType = -1; int attDefaultValue = -1; String use = attrDecl.getAttribute(SchemaSymbols.ATT_USE); boolean required = use.equals(SchemaSymbols.ATTVAL_REQUIRED); if (dv == null) { // REVISIT: Localize reportGenericSchemaError("could not resolve the type or get a null validator for datatype : " + fStringPool.toString(dataTypeSymbol)); } if (required) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED; } else { if (use.equals(SchemaSymbols.ATTVAL_FIXED)) { String fixed = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE); if (!fixed.equals("")) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_FIXED; attDefaultValue = fStringPool.addString(fixed); } } else if (use.equals(SchemaSymbols.ATTVAL_DEFAULT)) { // attribute default value String defaultValue = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE); if (!defaultValue.equals("")) { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_DEFAULT; attDefaultValue = fStringPool.addString(defaultValue); } } else if (use.equals(SchemaSymbols.ATTVAL_PROHIBITED)) { //REVISIT, TO DO. !!! attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED; //attDefaultValue = fStringPool.addString(""); } else { attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED; } // check default value is valid for the datatype. if (attType == XMLAttributeDecl.TYPE_SIMPLE && attDefaultValue != -1) { try { if (dv != null) //REVISIT dv.validate(fStringPool.toString(attDefaultValue), null); else reportSchemaError(SchemaMessageProvider.NoValidatorFor, new Object [] { datatype }); } catch (InvalidDatatypeValueException idve) { reportSchemaError(SchemaMessageProvider.IncorrectDefaultType, new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); } catch (Exception e) { e.printStackTrace(); System.out.println("Internal error in attribute datatype validation"); } } } int uriIndex = -1; if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fAttributeDefaultQualified || isTopLevel(attrDecl) ) { uriIndex = fTargetNSURI; } QName attQName = new QName(-1,attName,attName,uriIndex); if ( DEBUGGING ) System.out.println(" the dataType Validator for " + fStringPool.toString(attName) + " is " + dv); //put the top-levels in the attribute decl registry. if (isTopLevel(attrDecl)) { fTempAttributeDecl.datatypeValidator = dv; fTempAttributeDecl.name.setValues(attQName); fTempAttributeDecl.type = attType; fTempAttributeDecl.defaultType = attDefaultType; fTempAttributeDecl.list = attIsList; if (attDefaultValue != -1 ) { fTempAttributeDecl.defaultValue = new String(fStringPool.toString(attDefaultValue)); } fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl)); } // add attribute to attr decl pool in fSchemaGrammar, if (typeInfo != null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attQName, attType, dataTypeSymbol, attDefaultType, fStringPool.toString( attDefaultValue), dv, attIsList); } return -1; } // end of method traverseAttribute private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #addAttributeDeclFromAnotherSchema, schema uri : " + uriStr); return -1; } Hashtable attrRegistry = aGrammar.getAttirubteDeclRegistry(); if (attrRegistry == null) { // REVISIT: Localize reportGenericSchemaError("no attribute was defined in schema : " + uriStr); return -1; } XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name); if (tempAttrDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute named \"" + name + "\" was defined in schema : " + uriStr); return -1; } if (typeInfo!= null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, tempAttrDecl.name, tempAttrDecl.type, -1, tempAttrDecl.defaultType, tempAttrDecl.defaultValue, tempAttrDecl.datatypeValidator, tempAttrDecl.list); } return 0; } /* * * <attributeGroup * id = ID * name = NCName * ref = QName> * Content: (annotation?, (attribute|attributeGroup), anyAttribute?) * </> * */ private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception { // attribute name int attGrpName = fStringPool.addSymbol(attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME)); String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF); // attribute type int attType = -1; int enumeration = -1; if (!ref.equals("")) { if (XUtil.getFirstChildElement(attrGrpDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls); return -1; // TO DO // REVISIST: different NS, not supported yet. // REVISIT: Localize //reportGenericSchemaError("Feature not supported: see an attribute from different NS"); } Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart); if (referredAttrGrp != null) { traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attributegroup " + ref); } return -1; } for ( Element child = XUtil.getFirstChildElement(attrGrpDecl); child != null ; child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ traverseAttributeDecl(child, typeInfo); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child, typeInfo,anyAttDecls); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { anyAttDecls.addElement(traverseAnyAttribute(child)); break; } else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) { // REVISIT: what about appInfo } } return -1; } // end of method traverseAttributeGroup private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr); return -1; } // attribute name Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName); if (attGrpDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute group named \"" + attGrpName + "\" was defined in schema : " + uriStr); return -1; } NamespacesScope saveNSMapping = fNamespacesScope; int saveTargetNSUri = fTargetNSURI; fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()); fNamespacesScope = aGrammar.getNamespacesScope(); // attribute type int attType = -1; int enumeration = -1; for ( Element child = XUtil.getFirstChildElement(attGrpDecl); child != null ; child = XUtil.getNextSiblingElement(child)) { //child attribute couldn't be a top-level attribute DEFINITION, if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME); if ( childAttName.length() > 0 ) { Hashtable attDeclRegistry = aGrammar.getAttirubteDeclRegistry(); if (attDeclRegistry != null) { if (attDeclRegistry.get((Object)childAttName) != null ){ addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo); return -1; } } } else traverseAttributeDecl(child, typeInfo); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child, typeInfo, anyAttDecls); } else if ( child.getNodeName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { anyAttDecls.addElement(traverseAnyAttribute(child)); break; } else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) { // REVISIT: what about appInfo } } fNamespacesScope = saveNSMapping; fTargetNSURI = saveTargetNSUri; return -1; } // end of method traverseAttributeGroupFromAnotherSchema /** * Traverse element declaration: * <element * abstract = boolean * block = #all or (possibly empty) subset of {equivClass, extension, restriction} * default = string * equivClass = QName * final = #all or (possibly empty) subset of {extension, restriction} * fixed = string * form = qualified | unqualified * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * nullable = boolean * ref = QName * type = QName> * Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*) * </element> * * * The following are identity-constraint definitions * <unique * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </unique> * * <key * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </key> * * <keyref * id = ID * name = NCName * refer = QName> * Content: (annotation? , (selector , field+)) * </keyref> * * <selector> * Content: XPathExprApprox : An XPath expression * </selector> * * <field> * Content: XPathExprApprox : An XPath expression * </field> * * * @param elementDecl * @return * @exception Exception */ private QName traverseElementDecl(Element elementDecl) throws Exception { int contentSpecType = -1; int contentSpecNodeIndex = -1; int typeNameIndex = -1; int scopeDefined = -2; //signal a error if -2 gets gets through //cause scope can never be -2. DatatypeValidator dv = null; String name = elementDecl.getAttribute(SchemaSymbols.ATT_NAME); if ( DEBUGGING ) System.out.println("traversing element decl : " + name ); String ref = elementDecl.getAttribute(SchemaSymbols.ATT_REF); String type = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE); String minOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS); String maxOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS); String dflt = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String fixed = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED); String equivClass = elementDecl.getAttribute(SchemaSymbols.ATT_EQUIVCLASS); // form attribute String isQName = elementDecl.getAttribute(SchemaSymbols.ATT_FORM); String fromAnotherSchema = null; if (isTopLevel(elementDecl)) { int nameIndex = fStringPool.addSymbol(name); int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE); if (eltKey > -1 ) { return new QName(-1,nameIndex,nameIndex,fTargetNSURI); } } // parse out 'block', 'final', 'nullable', 'abstract' int blockSet = parseBlockSet(elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK)); int finalSet = parseFinalSet(elementDecl.getAttribute(SchemaSymbols.ATT_FINAL)); boolean isNullable = elementDecl.getAttribute (SchemaSymbols.ATT_NULLABLE).equals(SchemaSymbols.ATTVAL_TRUE)? true:false; boolean isAbstract = elementDecl.getAttribute (SchemaSymbols.ATT_ABSTRACT).equals(SchemaSymbols.ATTVAL_TRUE)? true:false; int elementMiscFlags = 0; if (isNullable) { elementMiscFlags += SchemaSymbols.NULLABLE; } if (isAbstract) { elementMiscFlags += SchemaSymbols.ABSTRACT; } //if this is a reference to a global element int attrCount = 0; if (!ref.equals("")) attrCount++; if (!type.equals("")) attrCount++; //REVISIT top level check for ref & archref if (attrCount > 1) reportSchemaError(SchemaMessageProvider.OneOfTypeRefArchRef, null); if (!ref.equals("")) { if (XUtil.getFirstChildElement(elementDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriString = resolvePrefixToURI(prefix); QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1, localpartIndex, fStringPool.addSymbol(ref), uriString != null ? fStringPool.addSymbol(uriString) : -1); //if from another schema, just return the element QName if (! uriString.equals(fTargetNSURIString) ) { return eltName; } int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE); //if not found, traverse the top level element that if referenced if (elementIndex == -1 ) { Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart); if (targetElement == null ) { // REVISIT: Localize reportGenericSchemaError("Element " + localpart + " not found in the Schema"); //REVISIT, for now, the QName anyway return eltName; //return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString)); } else { // do nothing here, other wise would cause infinite loop for // <element name="recur"><complexType><element ref="recur"> ... //eltName= traverseElementDecl(targetElement); } } return eltName; } // Handle the equivClass Element equivClassElementDecl = null; int equivClassElementDeclIndex = -1; boolean noErrorSoFar = true; String equivClassUri = null; String equivClassLocalpart = null; String equivClassFullName = null; ComplexTypeInfo equivClassEltTypeInfo = null; DatatypeValidator equivClassEltDV = null; if ( equivClass.length() > 0 ) { equivClassUri = resolvePrefixToURI(getPrefix(equivClass)); equivClassLocalpart = getLocalPart(equivClass); equivClassFullName = equivClassUri+","+equivClassLocalpart; if ( !equivClassUri.equals(fTargetNSURIString) ) { equivClassEltTypeInfo = getElementDeclTypeInfoFromNS(equivClassUri, equivClassLocalpart); if (equivClassEltTypeInfo == null) { equivClassEltDV = getElementDeclTypeValidatorFromNS(equivClassUri, equivClassLocalpart); if (equivClassEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +equivClassLocalpart + "' in schema '" + equivClassUri+"'"); } } } else { equivClassElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, equivClassLocalpart); if (equivClassElementDecl == null) { equivClassElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE); if ( equivClassElementDeclIndex == -1) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("Equivclass affiliation element " +equivClass +" in element declaration " +name); } } else { equivClassElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE); if ( equivClassElementDeclIndex == -1) { traverseElementDecl(equivClassElementDecl); equivClassElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE); } } if (equivClassElementDeclIndex != -1) { equivClassEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( equivClassElementDeclIndex ); if (equivClassEltTypeInfo == null) { fSchemaGrammar.getElementDecl(equivClassElementDeclIndex, fTempElementDecl); equivClassEltDV = fTempElementDecl.datatypeValidator; if (equivClassEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +equivClassLocalpart + "' in schema '" + equivClassUri+"'"); } } } } } // // resolving the type for this element right here // ComplexTypeInfo typeInfo = null; // element has a single child element, either a datatype or a type, null if primitive Element child = XUtil.getFirstChildElement(elementDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); boolean haveAnonType = false; // Handle Anonymous type if there is one if (child != null) { String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous complexType in element '" + name +"' has a name attribute"); } else typeNameIndex = traverseComplexTypeDecl(child); if (typeNameIndex != -1 ) { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse complexType error in element '" + name +"'"); } haveAnonType = true; } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { // TO DO: the Default and fixed attribute handling should be here. if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous simpleType in element '" + name +"' has a name attribute"); } else typeNameIndex = traverseSimpleTypeDecl(child); if (typeNameIndex != -1) { dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse simpleType error in element '" + name +"'"); } contentSpecType = XMLElementDecl.TYPE_SIMPLE; haveAnonType = true; } else if (type.equals("")) { // "ur-typed" leaf contentSpecType = XMLElementDecl.TYPE_ANY; //REVISIT: is this right? //contentSpecType = fStringPool.addSymbol("UR_TYPE"); // set occurrence count contentSpecNodeIndex = -1; } else { System.out.println("unhandled case in TraverseElementDecl"); } } // handle type="" here if (haveAnonType && (type.length()>0)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError( "Element '"+ name + "' have both a type attribute and a annoymous type child" ); } // type specified as an attribute and no child is type decl. else if (!type.equals("")) { if (equivClassElementDecl != null) { checkEquivClassOK(elementDecl, equivClassElementDecl); } String prefix = ""; String localpart = type; int colonptr = type.indexOf(":"); if ( colonptr > 0) { prefix = type.substring(0,colonptr); localpart = type.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); // check if the type is from the same Schema if ( !typeURI.equals(fTargetNSURIString) && !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI. fromAnotherSchema = typeURI; typeInfo = getTypeInfoFromNS(typeURI, localpart); if (typeInfo == null) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type " +localpart + " in schema " + typeURI); } } } else { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart); if (typeInfo == null) { dv = getDatatypeValidator(typeURI, localpart); if (dv == null ) if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } else { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (topleveltype != null) { if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { //then we found a recursive element using complexType. // REVISIT: this will be broken when recursing happens between 2 schemas int uriInd = -1; if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(name); QName tempQName = new QName(fCurrentScope, nameIndex, nameIndex, uriInd); fElementRecurseComplex.put(tempQName, localpart); return new QName(-1, nameIndex, nameIndex, uriInd); } else { typeNameIndex = traverseComplexTypeDecl( topleveltype ); typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } } else { topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { typeNameIndex = traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); // TO DO: the Default and fixed attribute handling should be here. } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } } } } } } else if (haveAnonType){ if (equivClassElementDecl != null ) { checkEquivClassOK(elementDecl, equivClassElementDecl); } } // this element is ur-type, check its equivClass afficliation. else { // if there is equivClass affiliation and not type defintion found for this element, // then grab equivClass affiliation's type and give it to this element if ( typeInfo == null && dv == null ) typeInfo = equivClassEltTypeInfo; if ( typeInfo == null && dv == null ) dv = equivClassEltDV; } if (typeInfo == null && dv==null) { if (noErrorSoFar) { // Actually this Element's type definition is ur-type; contentSpecType = XMLElementDecl.TYPE_ANY; // REVISIT, need to wait till we have wildcards implementation. // ADD attribute wildcards here } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError ("untyped element : " + name ); } } // if element belongs to a compelx type if (typeInfo!=null) { contentSpecNodeIndex = typeInfo.contentSpecHandle; contentSpecType = typeInfo.contentType; scopeDefined = typeInfo.scopeDefined; dv = typeInfo.datatypeValidator; } // if element belongs to a simple type if (dv!=null) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; } // // key/keyref/unique processing\ // child = XUtil.getFirstChildElement(elementDecl); Vector idConstraints = null; while (child != null){ String childName = child.getNodeName(); /**** if ( childName.equals(SchemaSymbols.ELT_KEY) ) { traverseKey(child, idCnstrt); } else if ( childName.equals(SchemaSymbols.ELT_KEYREF) ) { traverseKeyRef(child, idCnstrt); } else if ( childName.equals(SchemaSymbols.ELT_UNIQUE) ) { traverseUnique(child, idCnstrt); } if (idCnstrt!= null) { if (idConstraints != null) { idConstraints = new Vector(); } idConstraints.addElement(idCnstrt); } /****/ child = XUtil.getNextSiblingElement(child); } // // Create element decl // int elementNameIndex = fStringPool.addSymbol(name); int localpartIndex = elementNameIndex; int uriIndex = -1; int enclosingScope = fCurrentScope; if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified ) { uriIndex = fTargetNSURI; } if ( isTopLevel(elementDecl)) { uriIndex = fTargetNSURI; enclosingScope = TOP_LEVEL_SCOPE; } //There can never be two elements with the same name and different type in the same scope. int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope); if ( existSuchElementIndex > -1) { fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl); DatatypeValidator edv = fTempElementDecl.datatypeValidator; ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex); if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo)) || ((edv != null)&&(edv != dv)) ) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("duplicate element decl in the same scope : " + fStringPool.toString(localpartIndex)); } } QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex); // add element decl to pool int attrListHead = -1 ; // copy up attribute decls from type object if (typeInfo != null) { attrListHead = typeInfo.attlistHead; } int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined, contentSpecType, contentSpecNodeIndex, attrListHead, dv); if ( DEBUGGING ) { /***/ System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+"," + fStringPool.toString(eltQName.localpart) + ")"+ " eltType:"+type+" contentSpecType:"+contentSpecType+ " SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope + " scopeDefined: " +scopeDefined+"\n"); /***/ } if (typeInfo != null) { fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); } else { fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); // REVISIT: should we report error from here? } // mark element if its type belongs to different Schema. fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema); // set BlockSet, FinalSet, Nullable and Abstract for this element decl fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet); fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet); fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags); // setEquivClassElementFullName fSchemaGrammar.setElementDeclEquivClassElementFullName(elementIndex, equivClassFullName); return eltQName; }// end of method traverseElementDecl(Element) int getLocalPartIndex(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return fStringPool.addSymbol(localpart); } String getLocalPart(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return localpart; } int getPrefixIndex(String fullName){ int colonAt = fullName.indexOf(":"); String prefix = ""; if ( colonAt > -1 ) { prefix = fullName.substring(0,colonAt); } return fStringPool.addSymbol(prefix); } String getPrefix(String fullName){ int colonAt = fullName.indexOf(":"); String prefix = ""; if ( colonAt > -1 ) { prefix = fullName.substring(0,colonAt); } return prefix; } private void checkEquivClassOK(Element elementDecl, Element equivClassElementDecl){ //TO DO!! } private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception { Element child = XUtil.getFirstChildElement(fSchemaRootElement); if (child == null) { return null; } while (child != null ){ if ( child.getNodeName().equals(componentCategory)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) { return child; } } child = XUtil.getNextSiblingElement(child); } return null; } private boolean isTopLevel(Element component) { //REVISIT, is this the right way to check ? /**** if (component.getParentNode() == fSchemaRootElement ) { return true; } /****/ if (component.getParentNode().getNodeName().endsWith(SchemaSymbols.ELT_SCHEMA) ) { return true; } return false; } DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception { // The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry. // Now that we have only one DataTypeRegistry used by all schemas. this is not needed. /***** Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; DatatypeValidator dv = (DatatypeValidator) fSchemaGrammar.getDatatypeRegistry().getDatatypeValidator(localpart); return dv; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeValidatorFromNS"); } return null; /*****/ return getDatatypeValidator(newSchemaURI, localpart); } ComplexTypeInfo getTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; ComplexTypeInfo typeInfo = (ComplexTypeInfo) sGrammar.getComplexTypeRegistry().get(newSchemaURI+","+localpart); return typeInfo; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeInfoFromNS"); } return null; } DatatypeValidator getElementDeclTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI), fStringPool.addSymbol(localpart), TOP_LEVEL_SCOPE); DatatypeValidator dv = null; if (eltIndex>-1) { sGrammar.getElementDecl(eltIndex, fTempElementDecl); dv = fTempElementDecl.datatypeValidator; } else { reportGenericSchemaError("could not find global element : '" + localpart + " in the SchemaGrammar "+newSchemaURI); } return dv; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getELementDeclTypeValidatorFromNS"); } return null; } ComplexTypeInfo getElementDeclTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI), fStringPool.addSymbol(localpart), TOP_LEVEL_SCOPE); ComplexTypeInfo typeInfo = null; if (eltIndex>-1) { typeInfo = sGrammar.getElementComplexTypeInfo(eltIndex); } else { reportGenericSchemaError("could not find global element : '" + localpart + " in the SchemaGrammar "+newSchemaURI); } return typeInfo; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getElementDeclTypeInfoFromNS"); } return null; } /** * Traverse attributeGroup Declaration * * <attributeGroup * id = ID * ref = QName> * Content: (annotation?) * </> * * @param elementDecl * @exception Exception */ /*private int traverseAttributeGroupDecl( Element attributeGroupDecl ) throws Exception { int attributeGroupID = fStringPool.addSymbol( attributeGroupDecl.getAttribute( SchemaSymbols.ATTVAL_ID )); int attributeGroupName = fStringPool.addSymbol( attributeGroupDecl.getAttribute( SchemaSymbols.ATT_NAME )); return -1; }*/ /** * Traverse Group Declaration. * * <group * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * ref = QName> * Content: (annotation? , (element | group | all | choice | sequence | any)*) * <group/> * * @param elementDecl * @return * @exception Exception */ private int traverseGroupDecl( Element groupDecl ) throws Exception { String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME); String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF); if (!ref.equals("")) { if (XUtil.getFirstChildElement(groupDecl) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { return traverseGroupDeclFromAnotherSchema(localpart, uriStr); } int contentSpecIndex = -1; Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart); if (referredGroup == null) { // REVISIT: Localize reportGenericSchemaError("Group " + localpart + " not found in the Schema"); //REVISIT, this should be some custom Exception throw new Exception("Group " + localpart + " not found in the Schema"); } else { contentSpecIndex = traverseGroupDecl(referredGroup); } return contentSpecIndex; } boolean traverseElt = true; if (fCurrentScope == TOP_LEVEL_SCOPE) { traverseElt = false; } Element child = XUtil.getFirstChildElement(groupDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; int allChildren[] = null; int allChildCount = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; boolean seeAll = false; boolean seeParticle = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean illegalChild = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); //seeParticle = true; seeAll = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { illegalChild = true; reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if ( ! illegalChild ) { index = expandContentModel( index, child); } if (seeParticle && seeAll) { reportSchemaError( SchemaMessageProvider.GroupContentRestricted, new Object [] { "'all' needs to be 'the' only Child", childName}); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+ "schema uri: " + uriStr +", groupName: " + groupName); return -1; } Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName); if (groupDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no group named \"" + groupName + "\" was defined in schema : " + uriStr); return -1; } NamespacesScope saveNSMapping = fNamespacesScope; int saveTargetNSUri = fTargetNSURI; fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()); fNamespacesScope = aGrammar.getNamespacesScope(); boolean traverseElt = true; if (fCurrentScope == TOP_LEVEL_SCOPE) { traverseElt = false; } Element child = XUtil.getFirstChildElement(groupDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; int allChildren[] = null; int allChildCount = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); int childNameIndex = fStringPool.addSymbol(childName); String formAttrVal = child.getAttribute(SchemaSymbols.ATT_FORM); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); fNamespacesScope = saveNSMapping; fTargetNSURI = saveTargetNSUri; return left; } // end of method traverseGroupDeclFromAnotherSchema /** * * Traverse the Sequence declaration * * <sequence * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </sequence> * **/ int traverseSequence (Element sequenceDecl) throws Exception { Element child = XUtil.getFirstChildElement(sequenceDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } /** * * Traverse the Sequence declaration * * <choice * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </choice> * **/ int traverseChoice (Element choiceDecl) throws Exception { // REVISIT: traverseChoice, traverseSequence can be combined Element child = XUtil.getFirstChildElement(choiceDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int contentSpecType = 0; int csnType = 0; csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; contentSpecType = XMLElementDecl.TYPE_CHILDREN; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; hadContent = true; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); return left; } /** * * Traverse the "All" declaration * * <all * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </all> * **/ int traverseAll( Element allDecl) throws Exception { Element child = XUtil.getFirstChildElement(allDecl); while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)) child = XUtil.getNextSiblingElement(child); int allChildren[] = null; int allChildCount = 0; int left = -2; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; boolean seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if (seeParticle) { index = expandContentModel( index, child); } try { allChildren[allChildCount] = index; } catch (NullPointerException ne) { allChildren = new int[32]; allChildren[allChildCount] = index; } catch (ArrayIndexOutOfBoundsException ae) { int[] newArray = new int[allChildren.length*2]; System.arraycopy(allChildren, 0, newArray, 0, allChildren.length); allChildren[allChildCount] = index; } allChildCount++; } left = buildAllModel(allChildren,allChildCount); return left; } /** builds the all content model */ private int buildAllModel(int children[], int count) throws Exception { // build all model if (count > 1) { // create and initialize singletons XMLContentSpec choice = new XMLContentSpec(); choice.type = XMLContentSpec.CONTENTSPECNODE_CHOICE; choice.value = -1; choice.otherValue = -1; int[] exactChildren = new int[count]; System.arraycopy(children,0,exactChildren,0,count); // build all model sort(exactChildren, 0, count); int index = buildAllModel(exactChildren, 0, choice); return index; } if (count > 0) { return children[0]; } return -1; } /** Builds the all model. */ private int buildAllModel(int src[], int offset, XMLContentSpec choice) throws Exception { // swap last two places if (src.length - offset == 2) { int seqIndex = createSeq(src); if (choice.value == -1) { choice.value = seqIndex; } else { if (choice.otherValue != -1) { choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } choice.otherValue = seqIndex; } swap(src, offset, offset + 1); seqIndex = createSeq(src); if (choice.value == -1) { choice.value = seqIndex; } else { if (choice.otherValue != -1) { choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } choice.otherValue = seqIndex; } return fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false); } // recurse for (int i = offset; i < src.length - 1; i++) { choice.value = buildAllModel(src, offset + 1, choice); choice.otherValue = -1; sort(src, offset, src.length - offset); shift(src, offset, i + 1); } int choiceIndex = buildAllModel(src, offset + 1, choice); sort(src, offset, src.length - offset); return choiceIndex; } // buildAllModel(int[],int,ContentSpecNode,ContentSpecNode):int /** Creates a sequence. */ private int createSeq(int src[]) throws Exception { int left = src[0]; int right = src[1]; for (int i = 2; i < src.length; i++) { left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, left, right, false); right = src[i]; } return fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, left, right, false); } // createSeq(int[]):int /** Shifts a value into position. */ private void shift(int src[], int pos, int offset) { int temp = src[offset]; for (int i = offset; i > pos; i--) { src[i] = src[i - 1]; } src[pos] = temp; } // shift(int[],int,int) /** Simple sort. */ private void sort(int src[], final int offset, final int length) { for (int i = offset; i < offset + length - 1; i++) { int lowest = i; for (int j = i + 1; j < offset + length; j++) { if (src[j] < src[lowest]) { lowest = j; } } if (lowest != i) { int temp = src[i]; src[i] = src[lowest]; src[lowest] = temp; } } } // sort(int[],int,int) /** Swaps two values. */ private void swap(int src[], int i, int j) { int temp = src[i]; src[i] = src[j]; src[j] = temp; } // swap(int[],int,int) /** * Traverse Wildcard declaration * * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace} * processContents = lax | skip | strict> * Content: (annotation?) * </any> * @param elementDecl * @return * @exception Exception */ private int traverseWildcardDecl( Element wildcardDecl ) throws Exception { int wildcardID = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATTVAL_ID )); int wildcardMaxOccurs = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_MAXOCCURS )); int wildcardMinOccurs = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_MINOCCURS )); int wildcardNamespace = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_NAMESPACE )); int wildcardProcessContents = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_PROCESSCONTENTS )); int wildcardContent = fStringPool.addSymbol( wildcardDecl.getAttribute( SchemaSymbols.ATT_CONTENT )); return -1; } // utilities from Tom Watson's SchemaParser class // TO DO: Need to make this more conformant with Schema int type parsing private int parseInt (String intString) throws Exception { if ( intString.equals("*") ) { return SchemaSymbols.INFINITY; } else { return Integer.parseInt (intString); } } private int parseSimpleDerivedBy (String derivedByString) throws Exception { if ( derivedByString.equals (SchemaSymbols.ATTVAL_LIST) ) { return SchemaSymbols.LIST; } else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { return SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ("SimpleType: Invalid value for 'derivedBy'"); return -1; } } private int parseComplexDerivedBy (String derivedByString) throws Exception { if ( derivedByString.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { return SchemaSymbols.EXTENSION; } else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { return SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "ComplexType: Invalid value for 'derivedBy'" ); return -1; } } private int parseSimpleFinal (String finalString) throws Exception { if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST+SchemaSymbols.REPRODUCTION; } else { int enumerate = 0; int restrict = 0; int list = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ("restriction in set twice"); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( list == 0 ) { list = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ("list in set twice"); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid value (" + finalString + ")" ); } } return enumerate+restrict+list+reproduce; } } private int parseComplexContent (String contentString) throws Exception { if ( contentString.equals (SchemaSymbols.ATTVAL_EMPTY) ) { return XMLElementDecl.TYPE_EMPTY; } else if ( contentString.equals (SchemaSymbols.ATTVAL_ELEMENTONLY) ) { return XMLElementDecl.TYPE_CHILDREN; } else if ( contentString.equals (SchemaSymbols.ATTVAL_TEXTONLY) ) { return XMLElementDecl.TYPE_SIMPLE; } else if ( contentString.equals (SchemaSymbols.ATTVAL_MIXED) ) { return XMLElementDecl.TYPE_MIXED; } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid value for content" ); return -1; } } private int parseDerivationSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private int parseBlockSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) { if ( extend == 0 ) { extend = SchemaSymbols.EQUIVCLASS; } else { // REVISIT: Localize reportGenericSchemaError ( "'equivClass' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( extend == 0 ) { extend = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ( "'list' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private int parseFinalSet (String finalString) throws Exception { if ( finalString.equals ("#all") ) { return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION; } else { int extend = 0; int restrict = 0; int reproduce = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) { if ( extend == 0 ) { extend = SchemaSymbols.EQUIVCLASS; } else { // REVISIT: Localize reportGenericSchemaError ( "'equivClass' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) { if ( extend == 0 ) { extend = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ( "'list' already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict+reproduce; } } private void reportGenericSchemaError (String error) throws Exception { if (fErrorReporter == null) { System.err.println("__TraverseSchemaError__ : " + error); } else { reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error }); } } private void reportSchemaError(int major, Object args[]) throws Exception { if (fErrorReporter == null) { System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]); for (int i=0; i< args.length ; i++) { System.out.println((String)args[i]); } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, major, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } //Unit Test here public static void main(String args[] ) { if( args.length != 1 ) { System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" ); System.exit(0); } DOMParser parser = new DOMParser() { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} }; parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( args[0]); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar OutputFormat format = new OutputFormat( document ); java.io.StringWriter outWriter = new java.io.StringWriter(); XMLSerializer serial = new XMLSerializer( outWriter,format); TraverseSchema tst = null; try { Element root = document.getDocumentElement();// This is what we pass to TraverserSchema //serial.serialize( root ); //System.out.println(outWriter.toString()); tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() ); } catch (Exception e) { e.printStackTrace(System.err); } parser.getDocument(); } static class Resolver implements EntityResolver { private static final String SYSTEM[] = { "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd", "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd", "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent", }; private static final String PATH[] = { "structures.dtd", "datatypes.dtd", "versionInfo.ent", }; public InputSource resolveEntity(String publicId, String systemId) throws IOException { // looking for the schema DTDs? for (int i = 0; i < SYSTEM.length; i++) { if (systemId.equals(SYSTEM[i])) { InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i])); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } // use default resolution return null; } // resolveEntity(String,String):InputSource } // class Resolver static class ErrorHandler implements org.xml.sax.ErrorHandler { /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); throw ex; } // // Private methods // /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String } }
false
true
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception { String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE); String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK ); String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT); String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL ); String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID ); String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME); boolean isNamedType = false; if ( DEBUGGING ) System.out.println("traversing complex Type : " + typeName +","+base+","+content+"."); if (typeName.equals("")) { // gensym a unique name //typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++; typeName = "#"+fAnonTypeCount++; } else { fCurrentTypeNameStack.push(typeName); isNamedType = true; } if (isTopLevel(complexTypeDecl)) { String fullName = fTargetNSURIString+","+typeName; ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName); if (temp != null ) { return fStringPool.addSymbol(fullName); } } int scopeDefined = fScopeCount++; int previousScope = fCurrentScope; fCurrentScope = scopeDefined; Element child = null; int contentSpecType = -1; int csnType = 0; int left = -2; int right = -2; ComplexTypeInfo baseTypeInfo = null; //if base is a complexType; DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType DatatypeValidator simpleTypeValidator = null; int baseTypeSymbol = -1; String fullBaseName = ""; boolean baseIsSimpleSimple = false; boolean baseIsComplexSimple = false; boolean derivedByRestriction = true; boolean derivedByExtension = false; int baseContentSpecHandle = -1; Element baseTypeNode = null; //int parsedderivedBy = parseComplexDerivedBy(derivedBy); //handle the inhreitance here. if (base.length()>0) { //first check if derivedBy is present if (derivedBy.length() == 0) { // REVISIT: Localize reportGenericSchemaError("derivedBy must be present when base is present in " +SchemaSymbols.ELT_COMPLEXTYPE +" "+ typeName); } else { if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) { derivedByRestriction = false; } String prefix = ""; String localpart = base; int colonptr = base.indexOf(":"); if ( colonptr > 0) { prefix = base.substring(0,colonptr); localpart = base.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String typeURI = resolvePrefixToURI(prefix); // check if the base type is from the same Schema; if ( ! typeURI.equals(fTargetNSURIString) && ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{ baseTypeInfo = getTypeInfoFromNS(typeURI, localpart); if (baseTypeInfo == null) { baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart); if (baseTypeValidator == null) { //TO DO: report error here; System.out.println("Could not find base type " +localpart + " in schema " + typeURI); } else{ baseIsSimpleSimple = true; } } } else { fullBaseName = typeURI+","+localpart; // assume the base is a complexType and try to locate the base type first baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName); // if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet; // 2: base is SimpleTYpe; if (baseTypeInfo == null) { baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (baseTypeValidator == null) { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode ); baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName; } else { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode ); simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (simpleTypeValidator == null) { //TO DO: signal error here. } baseIsSimpleSimple = true; } else { // REVISIT: Localize reportGenericSchemaError("Base type could not be found : " + base); } } } else { simpleTypeValidator = baseTypeValidator; baseIsSimpleSimple = true; } } } //Schema Spec : 5.11: Complex Type Definition Properties Correct : 2 if (baseIsSimpleSimple && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName); } //if the base is a complexType if (baseTypeInfo != null ) { //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 // 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1 if (derivedByRestriction) { //REVISIT: check base Type's finalset does not include "restriction" } else { //REVISIT: check base Type's finalset doest not include "extension" } if ( baseTypeInfo.contentSpecHandle > -1) { if (derivedByRestriction) { //REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10 checkParticleDerivationOK(complexTypeDecl, baseTypeNode); } baseContentSpecHandle = baseTypeInfo.contentSpecHandle; } else if ( baseTypeInfo.datatypeValidator != null ) { baseTypeValidator = baseTypeInfo.datatypeValidator; baseIsComplexSimple = true; } } //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 if (baseIsComplexSimple && !derivedByRestriction ) { // REVISIT: Localize reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName); } } // END of if (derivedBy.length() == 0) {} else {} } // END of if (base.length() > 0) {} // skip refinement and annotations child = null; if (baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; int numEnumerationLiterals = 0; int numFacets = 0; Hashtable facetData = new Hashtable(); Vector enumData = new Vector(); //REVISIT: there is a better way to do this, for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) || child.getNodeName().equals(SchemaSymbols.ELT_SCALE) || child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) || child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) || child.getNodeName().equals(SchemaSymbols.ELT_DURATION) || child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) || child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) || child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)); child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeType() == Node.ELEMENT_NODE ) { Element facetElt = (Element) child; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE)); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( child ); } // TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } //if (numFacets > 0) // baseTypeValidator.setFacets(facetData, derivedBy ); if (numFacets > 0) { simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator, facetData, false ); } else simpleTypeValidator = baseTypeValidator; if (child != null) { // REVISIT: Localize reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName + "', because it restricts another complexSimpleType"); } } // if content = textonly, base is a datatype if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { //TO DO if (base.length() == 0) { simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); } else if ( baseTypeValidator == null && baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype reportSchemaError(SchemaMessageProvider.NotADatatype, new Object [] { base }); //REVISIT check forward refs //handle datatypes contentSpecType = XMLElementDecl.TYPE_SIMPLE; /**** left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, fStringPool.addSymbol(base), -1, false); /****/ } else { if (!baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_CHILDREN; } csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; boolean mixedContent = false; //REVISIT: is the default content " elementOnly" boolean elementContent = true; boolean textContent = false; boolean emptyContent = false; left = -2; right = -2; boolean hadContent = false; if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) { contentSpecType = XMLElementDecl.TYPE_EMPTY; emptyContent = true; elementContent = false; left = -1; // no contentSpecNode needed } else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) { contentSpecType = XMLElementDecl.TYPE_MIXED; mixedContent = true; elementContent = false; csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) { elementContent = true; } else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { textContent = true; elementContent = false; } if (mixedContent) { // add #PCDATA leaf left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, -1, // -1 means "#PCDATA" is name -1, false); csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } boolean seeParticle = false; boolean seeOtherParticle = false; boolean seeAll = false; for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; // to save the particle's contentSpec handle hadContent = true; seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { if (mixedContent || elementContent) { if ( DEBUGGING ) System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME)); QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; seeOtherParticle = true; } else { reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null); } } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); seeParticle = true; seeAll = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) || childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { break; // attr processing is done later on in this method } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) { //REVISIT, do nothing for annotation for now. } else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) { break; //REVISIT, do nothing for attribute wildcard for now. } else { // datatype qual if (!baseIsComplexSimple ) if (base.equals("")) reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "unrecogized child '"+childName+"' in compelx type "+typeName }); else reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "unrecogized child '"+childName+"' in compelx type '"+typeName+"' with base "+base }); } // if base is complextype with simpleType content, can't have any particle children at all. if (baseIsComplexSimple && seeParticle) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+", base type is complextype with simpleType content, can't have any particle children at all"); hadContent = false; left = index = -2; contentSpecType = XMLElementDecl.TYPE_SIMPLE; break; } // check the minOccurs and maxOccurs of the particle, and fix the // contentspec accordingly if (seeParticle) { index = expandContentModel(index, child); } //end of if (seeParticle) if (seeAll && seeOtherParticle) { // REVISIT: Localize reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName); } if (seeAll) { //TO DO: REVISIT //check the minOccurs = 1 and maxOccurs = 1 } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } //end looping through the children if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent) && (base.length() == 0 || ( base.length() > 0 && derivedByRestriction && !baseIsComplexSimple)) ) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); // REVISIT: Localize reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content " +"need to have at least one particle child"); } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); if (mixedContent && hadContent) { // set occurrence count left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, left, -1, false); } } // if derived by extension and base complextype has a content model, // compose the final content model by concatenating the base and the // current in sequence. if (!derivedByRestriction && baseContentSpecHandle > -1 ) { if (left == -2) { left = baseContentSpecHandle; } else left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, baseContentSpecHandle, left, false); } // REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType> if (content.length() == 0 && base.length() == 0 && left == -2) { contentSpecType = XMLElementDecl.TYPE_ANY; } if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) { if (base.length() > 0 && baseTypeInfo != null && baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) { contentSpecType = XMLElementDecl.TYPE_EMPTY; } } if ( DEBUGGING ) System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", " + baseContentSpecHandle +", " + left +", "+scopeDefined); ComplexTypeInfo typeInfo = new ComplexTypeInfo(); typeInfo.baseComplexTypeInfo = baseTypeInfo; typeInfo.baseDataTypeValidator = baseTypeValidator; int derivedByInt = -1; if (derivedBy.length() > 0) { derivedByInt = parseComplexDerivedBy(derivedBy); } typeInfo.derivedBy = derivedByInt; typeInfo.scopeDefined = scopeDefined; typeInfo.contentSpecHandle = left; typeInfo.contentType = contentSpecType; typeInfo.datatypeValidator = simpleTypeValidator; typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK)); typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL)); typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ; //add a template element to the grammar element decl pool. int typeNameIndex = fStringPool.addSymbol(typeName); int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined, contentSpecType, left, -1, simpleTypeValidator); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); // (attribute | attrGroupRef)* XMLAttributeDecl attWildcard = null; Vector anyAttDecls = new Vector(); for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+ ", base type has simpleType "+ "content and derivation method is"+ " 'restriction', can't have any "+ "attribute children at all"); break; } traverseAttributeDecl(child, typeInfo); } else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+", base "+ "type has simpleType content and "+ "derivation method is 'restriction',"+ " can't have any attribute children at all"); break; } traverseAttributeGroupDecl(child,typeInfo,anyAttDecls); } else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { attWildcard = traverseAnyAttribute(child); } } if (attWildcard != null) { XMLAttributeDecl fromGroup = null; final int count = anyAttDecls.size(); if ( count > 0) { fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0); for (int i=1; i<count; i++) { fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i)); } } if (fromGroup != null) { int saveProcessContents = attWildcard.defaultType; attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup); attWildcard.defaultType = saveProcessContents; } } else { //REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case } // merge in base type's attribute decls XMLAttributeDecl baseAttWildcard = null; if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) { int attDefIndex = baseTypeInfo.attlistHead; while ( attDefIndex > -1 ) { fTempAttributeDecl.clear(); fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl); if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) { if (attWildcard == null) { baseAttWildcard = fTempAttributeDecl; } attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } // if found a duplicate, if it is derived by restriction. then skip the one from the base type /**/ int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name); if ( temp > -1) { if (derivedByRestriction) { attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } } /**/ fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, fTempAttributeDecl.name, fTempAttributeDecl.type, fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType, fTempAttributeDecl.defaultValue, fTempAttributeDecl.datatypeValidator, fTempAttributeDecl.list); attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); } } // att wildcard will inserted after all attributes were processed if (attWildcard != null) { if (attWildcard.type != -1) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attWildcard.name, attWildcard.type, attWildcard.enumeration, attWildcard.defaultType, attWildcard.defaultValue, attWildcard.datatypeValidator, attWildcard.list); } else { //REVISIT: unclear in Schema spec if should report error here. } } else if (baseAttWildcard != null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, baseAttWildcard.name, baseAttWildcard.type, baseAttWildcard.enumeration, baseAttWildcard.defaultType, baseAttWildcard.defaultValue, baseAttWildcard.datatypeValidator, baseAttWildcard.list); } typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); if (!typeName.startsWith("#")) { typeName = fTargetNSURIString + "," + typeName; } typeInfo.typeName = new String(typeName); if ( DEBUGGING ) System.out.println("add complex Type to Registry: " + typeName +","+content+"."); fComplexTypeRegistry.put(typeName,typeInfo); // before exit the complex type definition, restore the scope, mainly for nested Anonymous Types fCurrentScope = previousScope; if (isNamedType) { fCurrentTypeNameStack.pop(); checkRecursingComplexType(); } //set template element's typeInfo fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo); typeNameIndex = fStringPool.addSymbol(typeName); return typeNameIndex; } // end of method: traverseComplexTypeDecl
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception { String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE); String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK ); String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT); String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY ); String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL ); String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID ); String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME); boolean isNamedType = false; if ( DEBUGGING ) System.out.println("traversing complex Type : " + typeName +","+base+","+content+"."); if (typeName.equals("")) { // gensym a unique name //typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++; typeName = "#"+fAnonTypeCount++; } else { fCurrentTypeNameStack.push(typeName); isNamedType = true; } if (isTopLevel(complexTypeDecl)) { String fullName = fTargetNSURIString+","+typeName; ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName); if (temp != null ) { return fStringPool.addSymbol(fullName); } } int scopeDefined = fScopeCount++; int previousScope = fCurrentScope; fCurrentScope = scopeDefined; Element child = null; int contentSpecType = -1; int csnType = 0; int left = -2; int right = -2; ComplexTypeInfo baseTypeInfo = null; //if base is a complexType; DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType DatatypeValidator simpleTypeValidator = null; int baseTypeSymbol = -1; String fullBaseName = ""; boolean baseIsSimpleSimple = false; boolean baseIsComplexSimple = false; boolean derivedByRestriction = true; boolean derivedByExtension = false; int baseContentSpecHandle = -1; Element baseTypeNode = null; //int parsedderivedBy = parseComplexDerivedBy(derivedBy); //handle the inhreitance here. if (base.length()>0) { //first check if derivedBy is present if (derivedBy.length() == 0) { // REVISIT: Localize reportGenericSchemaError("derivedBy must be present when base is present in " +SchemaSymbols.ELT_COMPLEXTYPE +" "+ typeName); } else { if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) { derivedByRestriction = false; } String prefix = ""; String localpart = base; int colonptr = base.indexOf(":"); if ( colonptr > 0) { prefix = base.substring(0,colonptr); localpart = base.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String typeURI = resolvePrefixToURI(prefix); // check if the base type is from the same Schema; if ( ! typeURI.equals(fTargetNSURIString) && ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{ baseTypeInfo = getTypeInfoFromNS(typeURI, localpart); if (baseTypeInfo == null) { baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart); if (baseTypeValidator == null) { //TO DO: report error here; System.out.println("Could not find base type " +localpart + " in schema " + typeURI); } else{ baseIsSimpleSimple = true; } } } else { fullBaseName = typeURI+","+localpart; // assume the base is a complexType and try to locate the base type first baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName); // if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet; // 2: base is SimpleTYpe; if (baseTypeInfo == null) { baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (baseTypeValidator == null) { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode ); baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName; } else { baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode ); simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart); if (simpleTypeValidator == null) { //TO DO: signal error here. } baseIsSimpleSimple = true; } else { // REVISIT: Localize reportGenericSchemaError("Base type could not be found : " + base); } } } else { simpleTypeValidator = baseTypeValidator; baseIsSimpleSimple = true; } } } //Schema Spec : 5.11: Complex Type Definition Properties Correct : 2 if (baseIsSimpleSimple && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName); } //if the base is a complexType if (baseTypeInfo != null ) { //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 // 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1 if (derivedByRestriction) { //REVISIT: check base Type's finalset does not include "restriction" } else { //REVISIT: check base Type's finalset doest not include "extension" } if ( baseTypeInfo.contentSpecHandle > -1) { if (derivedByRestriction) { //REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10 checkParticleDerivationOK(complexTypeDecl, baseTypeNode); } baseContentSpecHandle = baseTypeInfo.contentSpecHandle; } else if ( baseTypeInfo.datatypeValidator != null ) { baseTypeValidator = baseTypeInfo.datatypeValidator; baseIsComplexSimple = true; } } //Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1 if (baseIsComplexSimple && !derivedByRestriction ) { // REVISIT: Localize reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName); } } // END of if (derivedBy.length() == 0) {} else {} } // END of if (base.length() > 0) {} // skip refinement and annotations child = null; if (baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; int numEnumerationLiterals = 0; int numFacets = 0; Hashtable facetData = new Hashtable(); Vector enumData = new Vector(); //REVISIT: there is a better way to do this, for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) || child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) || child.getNodeName().equals(SchemaSymbols.ELT_SCALE) || child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) || child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) || child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) || child.getNodeName().equals(SchemaSymbols.ELT_DURATION) || child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) || child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) || child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION)); child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeType() == Node.ELEMENT_NODE ) { Element facetElt = (Element) child; numFacets++; if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE)); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){ traverseAnnotationDecl( child ); } // TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over } else { facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } } if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } //if (numFacets > 0) // baseTypeValidator.setFacets(facetData, derivedBy ); if (numFacets > 0) { simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator, facetData, false ); } else simpleTypeValidator = baseTypeValidator; if (child != null) { // REVISIT: Localize reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName + "', because it restricts another complexSimpleType"); } } // if content = textonly, base is a datatype if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { //TO DO if (base.length() == 0) { simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); } else if ( baseTypeValidator == null && baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype reportSchemaError(SchemaMessageProvider.NotADatatype, new Object [] { base }); //REVISIT check forward refs //handle datatypes contentSpecType = XMLElementDecl.TYPE_SIMPLE; /**** left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, fStringPool.addSymbol(base), -1, false); /****/ } else { if (!baseIsComplexSimple) { contentSpecType = XMLElementDecl.TYPE_CHILDREN; } csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; boolean mixedContent = false; //REVISIT: is the default content " elementOnly" boolean elementContent = true; boolean textContent = false; boolean emptyContent = false; left = -2; right = -2; boolean hadContent = false; if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) { contentSpecType = XMLElementDecl.TYPE_EMPTY; emptyContent = true; elementContent = false; left = -1; // no contentSpecNode needed } else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) { contentSpecType = XMLElementDecl.TYPE_MIXED; mixedContent = true; elementContent = false; csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) { elementContent = true; } else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) { textContent = true; elementContent = false; } if (mixedContent) { // add #PCDATA leaf left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, -1, // -1 means "#PCDATA" is name -1, false); csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; } boolean seeParticle = false; boolean seeOtherParticle = false; boolean seeAll = false; for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; // to save the particle's contentSpec handle hadContent = true; seeParticle = false; String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { if (mixedContent || elementContent) { if ( DEBUGGING ) System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME)); QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; seeOtherParticle = true; } else { reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null); } } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); seeParticle = true; seeAll = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) || childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { break; // attr processing is done later on in this method } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; seeOtherParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) { //REVISIT, do nothing for annotation for now. } else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) { break; //REVISIT, do nothing for attribute wildcard for now. } else { // datatype qual if (!baseIsComplexSimple ) if (base.equals("")) reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "unrecognized child '"+childName+"' in complex type "+typeName }); else reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "unrecognized child '"+childName+"' in complex type '"+typeName+"' with base "+base }); } // if base is complextype with simpleType content, can't have any particle children at all. if (baseIsComplexSimple && seeParticle) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+", base type is complexType with simpleType content, can't have any particle children at all"); hadContent = false; left = index = -2; contentSpecType = XMLElementDecl.TYPE_SIMPLE; break; } // check the minOccurs and maxOccurs of the particle, and fix the // contentspec accordingly if (seeParticle) { index = expandContentModel(index, child); } //end of if (seeParticle) if (seeAll && seeOtherParticle) { // REVISIT: Localize reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName); } if (seeAll) { //TO DO: REVISIT //check the minOccurs = 1 and maxOccurs = 1 } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } //end looping through the children if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent) && (base.length() == 0 || ( base.length() > 0 && derivedByRestriction && !baseIsComplexSimple)) ) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING); // REVISIT: Localize reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content " +"need to have at least one particle child"); } if (hadContent && right != -2) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); if (mixedContent && hadContent) { // set occurrence count left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, left, -1, false); } } // if derived by extension and base complextype has a content model, // compose the final content model by concatenating the base and the // current in sequence. if (!derivedByRestriction && baseContentSpecHandle > -1 ) { if (left == -2) { left = baseContentSpecHandle; } else left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, baseContentSpecHandle, left, false); } // REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType> if (content.length() == 0 && base.length() == 0 && left == -2) { contentSpecType = XMLElementDecl.TYPE_ANY; } if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) { if (base.length() > 0 && baseTypeInfo != null && baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) { contentSpecType = XMLElementDecl.TYPE_EMPTY; } } if ( DEBUGGING ) System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", " + baseContentSpecHandle +", " + left +", "+scopeDefined); ComplexTypeInfo typeInfo = new ComplexTypeInfo(); typeInfo.baseComplexTypeInfo = baseTypeInfo; typeInfo.baseDataTypeValidator = baseTypeValidator; int derivedByInt = -1; if (derivedBy.length() > 0) { derivedByInt = parseComplexDerivedBy(derivedBy); } typeInfo.derivedBy = derivedByInt; typeInfo.scopeDefined = scopeDefined; typeInfo.contentSpecHandle = left; typeInfo.contentType = contentSpecType; typeInfo.datatypeValidator = simpleTypeValidator; typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK)); typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL)); typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ; //add a template element to the grammar element decl pool. int typeNameIndex = fStringPool.addSymbol(typeName); int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined, contentSpecType, left, -1, simpleTypeValidator); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); // (attribute | attrGroupRef)* XMLAttributeDecl attWildcard = null; Vector anyAttDecls = new Vector(); for (child = XUtil.getFirstChildElement(complexTypeDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String childName = child.getNodeName(); if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+ ", base type has simpleType "+ "content and derivation method is"+ " 'restriction', can't have any "+ "attribute children at all"); break; } traverseAttributeDecl(child, typeInfo); } else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) { // REVISIT: Localize reportGenericSchemaError("In complexType "+typeName+", base "+ "type has simpleType content and "+ "derivation method is 'restriction',"+ " can't have any attribute children at all"); break; } traverseAttributeGroupDecl(child,typeInfo,anyAttDecls); } else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { attWildcard = traverseAnyAttribute(child); } } if (attWildcard != null) { XMLAttributeDecl fromGroup = null; final int count = anyAttDecls.size(); if ( count > 0) { fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0); for (int i=1; i<count; i++) { fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i)); } } if (fromGroup != null) { int saveProcessContents = attWildcard.defaultType; attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup); attWildcard.defaultType = saveProcessContents; } } else { //REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case } // merge in base type's attribute decls XMLAttributeDecl baseAttWildcard = null; if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) { int attDefIndex = baseTypeInfo.attlistHead; while ( attDefIndex > -1 ) { fTempAttributeDecl.clear(); fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl); if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) { if (attWildcard == null) { baseAttWildcard = fTempAttributeDecl; } attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } // if found a duplicate, if it is derived by restriction. then skip the one from the base type /**/ int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name); if ( temp > -1) { if (derivedByRestriction) { attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } } /**/ fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, fTempAttributeDecl.name, fTempAttributeDecl.type, fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType, fTempAttributeDecl.defaultValue, fTempAttributeDecl.datatypeValidator, fTempAttributeDecl.list); attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); } } // att wildcard will inserted after all attributes were processed if (attWildcard != null) { if (attWildcard.type != -1) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attWildcard.name, attWildcard.type, attWildcard.enumeration, attWildcard.defaultType, attWildcard.defaultValue, attWildcard.datatypeValidator, attWildcard.list); } else { //REVISIT: unclear in Schema spec if should report error here. } } else if (baseAttWildcard != null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, baseAttWildcard.name, baseAttWildcard.type, baseAttWildcard.enumeration, baseAttWildcard.defaultType, baseAttWildcard.defaultValue, baseAttWildcard.datatypeValidator, baseAttWildcard.list); } typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex); if (!typeName.startsWith("#")) { typeName = fTargetNSURIString + "," + typeName; } typeInfo.typeName = new String(typeName); if ( DEBUGGING ) System.out.println("add complex Type to Registry: " + typeName +","+content+"."); fComplexTypeRegistry.put(typeName,typeInfo); // before exit the complex type definition, restore the scope, mainly for nested Anonymous Types fCurrentScope = previousScope; if (isNamedType) { fCurrentTypeNameStack.pop(); checkRecursingComplexType(); } //set template element's typeInfo fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo); typeNameIndex = fStringPool.addSymbol(typeName); return typeNameIndex; } // end of method: traverseComplexTypeDecl
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java index 5243c8a18..5ff55ca29 100644 --- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java +++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java @@ -1,281 +1,286 @@ package org.eclipse.ptp.rtsystem.ompi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.BitSet; import org.eclipse.core.runtime.Preferences; import org.eclipse.ptp.core.ControlSystemChoices; import org.eclipse.ptp.core.IModelManager; import org.eclipse.ptp.core.MonitoringSystemChoices; import org.eclipse.ptp.core.PTPCorePlugin; import org.eclipse.ptp.core.PreferenceConstants; import org.eclipse.ptp.core.util.Queue; import org.eclipse.ptp.internal.core.CoreUtils; import org.eclipse.ptp.rtsystem.IRuntimeProxy; import org.eclipse.ptp.rtsystem.proxy.ProxyRuntimeClient; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeErrorEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNewJobEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodeAttributeEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodesEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessAttributeEvent; import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessesEvent; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class OMPIProxyRuntimeClient extends ProxyRuntimeClient implements IRuntimeProxy, IProxyRuntimeEventListener { protected Queue events = new Queue(); protected BitSet waitEvents = new BitSet(); protected IModelManager modelManager; public OMPIProxyRuntimeClient(IModelManager modelManager) { super(); super.addRuntimeEventListener(this); this.modelManager = modelManager; } public int runJob(String[] args) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NEWJOB); run(args); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNewJobEvent)event).getJobID(); } public int getJobProcesses(int jobID) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCS); getProcesses(jobID); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessesEvent)event).getNumProcs(); } public String[] getProcessAttributesBlocking(int jobID, int procID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR); getProcessAttribute(jobID, procID, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessAttributeEvent)event).getValues(); } public String[] getAllProcessesAttribuesBlocking(int jobID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR); getProcessAttribute(jobID, -1, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeProcessAttributeEvent)event).getValues(); } public int getNumNodesBlocking(int machineID) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODES); getNodes(machineID); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodesEvent)event).getNumNodes(); } public String[] getNodeAttributesBlocking(int machID, int nodeID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR); getNodeAttribute(machID, nodeID, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodeAttributeEvent)event).getValues(); } public String[] getAllNodesAttributesBlocking(int machID, String keys) throws IOException { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR); getNodeAttribute(machID, -1, keys); IProxyRuntimeEvent event = waitForRuntimeEvent(); return ((ProxyRuntimeNodeAttributeEvent)event).getValues(); } public boolean startup() { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); String orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(proxyPath.equals("") || orted_path.equals("")) { - Shell s = Display.getDefault().getActiveShell(); - System.out.println("SHELL = "+s); - if(s != null) - new OMPIPrefsDialog(s).open(); + final Display display = Display.getDefault(); + display.syncExec(new Runnable() { + public void run() { + Shell s = display.getActiveShell(); + System.out.println("SHELL = "+s); + if(s != null) + new OMPIPrefsDialog(s).open(); + } + }); } proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(orted_path.equals("")) { String err = "Some error occurred trying to spawn the ORTEd (ORTE daemon). Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTEd Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd; Runtime rt = Runtime.getRuntime (); cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = rt.exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { CoreUtils.showErrorDialog("Running Proxy Server", line, null); } /* String line; while ((line = buf_reader.readLine ()) != null) { System.out.println ("ORTE PROXY SERVER: "+line); } */ } catch(IOException e) { String err; err = "Error running proxy server with command: '"+cmd+"'."; e.printStackTrace(); System.out.println(err); CoreUtils.showErrorDialog("Running Proxy Server", err, null); } } }; runThread.start(); System.out.println("Waiting on accept."); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); System.exit(1); } String ompi_bin_path = orted_path.substring(0, orted_path.lastIndexOf("/")); String orted_args = preferences.getString(PreferenceConstants.ORTE_ORTED_ARGS); String orted_full = orted_path + " " + orted_args; System.out.println("ORTED = "+orted_full); /* start the orted */ String[] split_args = orted_args.split("\\s"); for (int x=0; x<split_args.length; x++) System.out.println("["+x+"] = "+split_args[x]); String[] split_path = orted_path.split("\\/"); for(int x=0; x<split_path.length; x++) System.out.println("["+x+"] = "+split_path[x]); String str_arg, arg_array_as_string; arg_array_as_string = new String(""); for(int i=0; i<split_args.length; i++) { arg_array_as_string = arg_array_as_string + " " + split_args[i]; } str_arg = ompi_bin_path + " " + orted_path + " " + split_path[split_path.length - 1] + arg_array_as_string; try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON", str_arg); waitForRuntimeEvent(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } public void shutdown() { try { System.out.println("OMPIProxyRuntimeClient shutting down server..."); setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sessionFinish(); waitForRuntimeEvent(); System.out.println("OMPIProxyRuntimeClient shut down."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void setWaitEvent(int eventID) { waitEvents.set(eventID); waitEvents.set(IProxyRuntimeEvent.EVENT_RUNTIME_ERROR); // always check for errors } private synchronized IProxyRuntimeEvent waitForRuntimeEvent() throws IOException { IProxyRuntimeEvent event = null; try { System.out.println("OMPIProxyRuntimeClient waiting on " + waitEvents.toString()); while (this.events.isEmpty()) wait(); System.out.println("OMPIProxyRuntimeClient awoke!"); event = (IProxyRuntimeEvent) this.events.removeItem(); if (event instanceof ProxyRuntimeErrorEvent) { waitEvents.clear(); throw new IOException(((ProxyRuntimeErrorEvent)event).getErrorMessage()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } waitEvents.clear(); return event; } /* * Only handle events we're interested in */ public synchronized void handleEvent(IProxyRuntimeEvent e) { System.out.println("OMPIProxyRuntimeClient got event: " + e.toString()); if (waitEvents.get(e.getEventID())) { System.out.println("OMPIProxyRuntimeClient notifying..."); this.events.addItem(e); notifyAll(); } } }
true
true
public boolean startup() { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); String orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(proxyPath.equals("") || orted_path.equals("")) { Shell s = Display.getDefault().getActiveShell(); System.out.println("SHELL = "+s); if(s != null) new OMPIPrefsDialog(s).open(); } proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(orted_path.equals("")) { String err = "Some error occurred trying to spawn the ORTEd (ORTE daemon). Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTEd Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd; Runtime rt = Runtime.getRuntime (); cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = rt.exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { CoreUtils.showErrorDialog("Running Proxy Server", line, null); } /* String line; while ((line = buf_reader.readLine ()) != null) { System.out.println ("ORTE PROXY SERVER: "+line); } */ } catch(IOException e) { String err; err = "Error running proxy server with command: '"+cmd+"'."; e.printStackTrace(); System.out.println(err); CoreUtils.showErrorDialog("Running Proxy Server", err, null); } } }; runThread.start(); System.out.println("Waiting on accept."); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); System.exit(1); } String ompi_bin_path = orted_path.substring(0, orted_path.lastIndexOf("/")); String orted_args = preferences.getString(PreferenceConstants.ORTE_ORTED_ARGS); String orted_full = orted_path + " " + orted_args; System.out.println("ORTED = "+orted_full); /* start the orted */ String[] split_args = orted_args.split("\\s"); for (int x=0; x<split_args.length; x++) System.out.println("["+x+"] = "+split_args[x]); String[] split_path = orted_path.split("\\/"); for(int x=0; x<split_path.length; x++) System.out.println("["+x+"] = "+split_path[x]); String str_arg, arg_array_as_string; arg_array_as_string = new String(""); for(int i=0; i<split_args.length; i++) { arg_array_as_string = arg_array_as_string + " " + split_args[i]; } str_arg = ompi_bin_path + " " + orted_path + " " + split_path[split_path.length - 1] + arg_array_as_string; try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON", str_arg); waitForRuntimeEvent(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
public boolean startup() { System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . ."); Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences(); String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); String orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(proxyPath.equals("") || orted_path.equals("")) { final Display display = Display.getDefault(); display.syncExec(new Runnable() { public void run() { Shell s = display.getActiveShell(); System.out.println("SHELL = "+s); if(s != null) new OMPIPrefsDialog(s).open(); } }); } proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); System.out.println("ORTE_SERVER path = '"+proxyPath+"'"); if(proxyPath.equals("")) { String err = "Could not start the ORTE server. Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTE Server Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } orted_path = preferences.getString(PreferenceConstants.ORTE_ORTED_PATH); System.out.println("ORTED path = '"+orted_path+"'"); if(orted_path.equals("")) { String err = "Some error occurred trying to spawn the ORTEd (ORTE daemon). Check the "+ "PTP/Open RTE preferences page and be certain that the path and arguments "+ "are correct. Defaulting to Simulation Mode."; System.err.println(err); CoreUtils.showErrorDialog("ORTEd Start Failure", err, null); int MSI = MonitoringSystemChoices.SIMULATED; int CSI = ControlSystemChoices.SIMULATED; preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI); preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI); PTPCorePlugin.getDefault().savePluginPreferences(); return false; } final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH); try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED); sessionCreate(); Thread runThread = new Thread("Proxy Server Thread") { public void run() { String cmd; Runtime rt = Runtime.getRuntime (); cmd = proxyPath2 + " --port="+getSessionPort(); System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'"); try { Process process = rt.exec(cmd); InputStreamReader reader = new InputStreamReader (process.getErrorStream()); BufferedReader buf_reader = new BufferedReader (reader); String line = buf_reader.readLine(); if (line != null) { CoreUtils.showErrorDialog("Running Proxy Server", line, null); } /* String line; while ((line = buf_reader.readLine ()) != null) { System.out.println ("ORTE PROXY SERVER: "+line); } */ } catch(IOException e) { String err; err = "Error running proxy server with command: '"+cmd+"'."; e.printStackTrace(); System.out.println(err); CoreUtils.showErrorDialog("Running Proxy Server", err, null); } } }; runThread.start(); System.out.println("Waiting on accept."); waitForRuntimeEvent(); } catch (IOException e) { System.err.println("Exception starting up proxy. :("); System.exit(1); } String ompi_bin_path = orted_path.substring(0, orted_path.lastIndexOf("/")); String orted_args = preferences.getString(PreferenceConstants.ORTE_ORTED_ARGS); String orted_full = orted_path + " " + orted_args; System.out.println("ORTED = "+orted_full); /* start the orted */ String[] split_args = orted_args.split("\\s"); for (int x=0; x<split_args.length; x++) System.out.println("["+x+"] = "+split_args[x]); String[] split_path = orted_path.split("\\/"); for(int x=0; x<split_path.length; x++) System.out.println("["+x+"] = "+split_path[x]); String str_arg, arg_array_as_string; arg_array_as_string = new String(""); for(int i=0; i<split_args.length; i++) { arg_array_as_string = arg_array_as_string + " " + split_args[i]; } str_arg = ompi_bin_path + " " + orted_path + " " + split_path[split_path.length - 1] + arg_array_as_string; try { setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK); sendCommand("STARTDAEMON", str_arg); waitForRuntimeEvent(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
diff --git a/ini/trakem2/display/Pipe.java b/ini/trakem2/display/Pipe.java index 082a44e4..1bf62504 100644 --- a/ini/trakem2/display/Pipe.java +++ b/ini/trakem2/display/Pipe.java @@ -1,2165 +1,2166 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.display; import ij.measure.Calibration; import ij.measure.ResultsTable; import ini.trakem2.Project; import ini.trakem2.utils.IJError; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; import ini.trakem2.utils.M; import ini.trakem2.utils.Search; import ini.trakem2.utils.Vector3; import ini.trakem2.persistence.DBObject; import ini.trakem2.vector.VectorString3D; import java.awt.Color; import java.awt.Rectangle; import java.awt.Polygon; import java.awt.event.MouseEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Composite; import java.awt.AlphaComposite; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Area; import java.awt.Shape; import javax.vecmath.Point3f; public class Pipe extends ZDisplayable implements Line3D { /**The number of points.*/ protected int n_points; /**The array of clicked points.*/ protected double[][] p; /**The array of left control points, one for each clicked point.*/ protected double[][] p_l; /**The array of right control points, one for each clicked point.*/ protected double[][] p_r; /**The array of interpolated points generated from p, p_l and p_r.*/ protected double[][] p_i = new double[2][0]; /**The array of Layers over which the points of this pipe live */ protected long[] p_layer; /**The width of each point. */ protected double[] p_width; /**The interpolated width for each interpolated point. */ protected double[] p_width_i = new double[0]; /** Every new Pipe will have, for its first point, the last user-adjusted radius value. */ static private double last_radius = -1; public Pipe(Project project, String title, double x, double y) { super(project, title, x, y); n_points = 0; p = new double[2][5]; p_l = new double[2][5]; p_r = new double[2][5]; p_layer = new long[5]; // the ids of the layers in which each point lays p_width = new double[5]; addToDatabase(); } /** Construct an unloaded Pipe from the database. Points will be loaded later, when needed. */ public Pipe(Project project, long id, String title, double width, double height, float alpha, boolean visible, Color color, boolean locked, AffineTransform at) { super(project, id, title, locked, at, width, height); this.visible = visible; this.alpha = alpha; this.visible = visible; this.color = color; this.n_points = -1; //used as a flag to signal "I have points, but unloaded" } /** Construct a Pipe from an XML entry. */ public Pipe(Project project, long id, HashMap ht, HashMap ht_links) { super(project, id, ht, ht_links); // parse specific data for (Iterator it = ht.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); String key = (String)entry.getKey(); String data = (String)entry.getValue(); if (key.equals("d")) { // parse the points // parse the SVG points data ArrayList al_p = new ArrayList(); ArrayList al_p_r = new ArrayList(); ArrayList al_p_l = new ArrayList();// needs shifting, inserting one point at the beginning if not closed. // sequence is: M p[0],p[1] C p_r[0],p_r[1] p_l[0],p_l[1] and repeat without the M, and finishes with the last p[0],p[1]. If closed, appended at the end is p_r[0],p_r[1] p_l[0],p_l[1] // first point: int i_start = data.indexOf('M'); int i_end = data.indexOf('C'); String point = data.substring(i_start+1, i_end).trim(); al_p.add(point); boolean go = true; while (go) { i_start = i_end; i_end = data.indexOf('C', i_end+1); if (-1 == i_end) { i_end = data.length() -1; go = false; } String txt = data.substring(i_start+1, i_end).trim(); // eliminate double spaces while (-1 != txt.indexOf(" ")) { txt = txt.replaceAll(" ", " "); } // reduce ", " and " ," to "," txt = txt.replaceAll(" ,", ","); txt = txt.replaceAll(", ", ","); // cut by spaces String[] points = txt.split(" "); if (3 == points.length) { al_p_r.add(points[0]); al_p_l.add(points[1]); al_p.add(points[2]); } else { // error Utils.log("Pipe constructor from XML: error at parsing points."); } // example: C 34.5,45.6 45.7,23.0 34.8, 78.0 C .. } // fix missing control points al_p_l.add(0, al_p.get(0)); al_p_r.add(al_p.get(al_p.size() -1)); // sanity check: if (!(al_p.size() == al_p_l.size() && al_p_l.size() == al_p_r.size())) { Utils.log2("Pipe XML parsing: Disagreement in the number of points:\n\tp.length=" + al_p.size() + "\n\tp_l.length=" + al_p_l.size() + "\n\tp_r.length=" + al_p_r.size()); } // Now parse the points this.n_points = al_p.size(); this.p = new double[2][n_points]; this.p_l = new double[2][n_points]; this.p_r = new double[2][n_points]; for (int i=0; i<n_points; i++) { String[] sp = ((String)al_p.get(i)).split(","); p[0][i] = Double.parseDouble(sp[0]); p[1][i] = Double.parseDouble(sp[1]); sp = ((String)al_p_l.get(i)).split(","); p_l[0][i] = Double.parseDouble(sp[0]); p_l[1][i] = Double.parseDouble(sp[1]); sp = ((String)al_p_r.get(i)).split(","); p_r[0][i] = Double.parseDouble(sp[0]); p_r[1][i] = Double.parseDouble(sp[1]); } } else if (key.equals("layer_ids")) { // parse comma-separated list of layer ids. Creates empty Layer instances with the proper id, that will be replaced later. String[] layer_ids = data.replaceAll(" ", "").trim().split(","); this.p_layer = new long[layer_ids.length]; for (int i=0; i<layer_ids.length; i++) { this.p_layer[i] = Long.parseLong(layer_ids[i]); } } else if (key.equals("p_width")) { String[] widths = data.replaceAll(" ", "").trim().split(","); this.p_width = new double[widths.length]; for (int i=0; i<widths.length; i++) { this.p_width[i] = Double.parseDouble(widths[i]); } } } // finish up this.p_i = new double[2][0]; // empty this.p_width_i = new double[0]; generateInterpolatedPoints(0.05); if (null == this.p) { this.n_points = 0; this.p = new double[2][0]; this.p_l = new double[2][0]; this.p_r = new double[2][0]; this.p_width = new double[0]; this.p_layer = new long[0]; } // sanity check: if (!(n_points == p[0].length && p[0].length == p_width.length && p_width.length == p_layer.length)) { Utils.log2("Pipe at parsing XML: inconsistent number of points for id=" + id); Utils.log2("\tn_points: " + n_points + " p.length: " + p[0].length + " p_width.length: " + p_width.length + " p_layer.length: " + p_layer.length); } } /**Increase the size of the arrays by 5.*/ synchronized private void enlargeArrays() { //catch length int length = p[0].length; //make copies double[][] p_copy = new double[2][length + 5]; double[][] p_l_copy = new double[2][length + 5]; double[][] p_r_copy = new double[2][length + 5]; long[] p_layer_copy = new long[length + 5]; double[] p_width_copy = new double[length + 5]; //copy values System.arraycopy(p[0], 0, p_copy[0], 0, length); System.arraycopy(p[1], 0, p_copy[1], 0, length); System.arraycopy(p_l[0], 0, p_l_copy[0], 0, length); System.arraycopy(p_l[1], 0, p_l_copy[1], 0, length); System.arraycopy(p_r[0], 0, p_r_copy[0], 0, length); System.arraycopy(p_r[1], 0, p_r_copy[1], 0, length); System.arraycopy(p_layer, 0, p_layer_copy, 0, length); System.arraycopy(p_width, 0, p_width_copy, 0, length); //assign them this.p = p_copy; this.p_l = p_l_copy; this.p_r = p_r_copy; this.p_layer = p_layer_copy; this.p_width = p_width_copy; } /**Find a point in an array, with a precision dependent on the magnification. Only points in the current layer are found, the rest are ignored. Returns -1 if none found. */ synchronized protected int findPoint(double[][] a, int x_p, int y_p, double magnification) { int index = -1; double d = (10.0D / magnification); if (d < 2) d = 2; double min_dist = Double.MAX_VALUE; long i_layer = Display.getFrontLayer(this.project).getId(); for (int i=0; i<n_points; i++) { double dist = Math.abs(x_p - a[0][i]) + Math.abs(y_p - a[1][i]); if (i_layer == p_layer[i] && dist <= d && dist <= min_dist) { min_dist = dist; index = i; } } return index; } /**Remove a point from the bezier backbone and its two associated control points.*/ synchronized protected void removePoint(int index) { // check preconditions: if (index < 0) { return; } else if (n_points - 1 == index) { //last point out n_points--; } else { //one point out (but not the last) --n_points; // shift all points after 'index' one position to the left: for (int i=index; i<n_points; i++) { p[0][i] = p[0][i+1]; //the +1 doesn't fail ever because the n_points has been adjusted above, but the arrays are still the same size. The case of deleting the last point is taken care above. p[1][i] = p[1][i+1]; p_l[0][i] = p_l[0][i+1]; p_l[1][i] = p_l[1][i+1]; p_r[0][i] = p_r[0][i+1]; p_r[1][i] = p_r[1][i+1]; p_layer[i] = p_layer[i+1]; p_width[i] = p_width[i+1]; } } //update in database updateInDatabase("points"); } /**Calculate distance from one point to another.*/ static public double distance(final double x1, final double y1, final double x2, final double y2) { return (Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))); } /**Move backbone point by the given deltas.*/ protected void dragPoint(int index, int dx, int dy) { p[0][index] += dx; p[1][index] += dy; p_l[0][index] += dx; p_l[1][index] += dy; p_r[0][index] += dx; p_r[1][index] += dy; } /**Set the control points to the same value as the backbone point which they control.*/ protected void resetControlPoints(int index) { p_l[0][index] = p[0][index]; p_l[1][index] = p[1][index]; p_r[0][index] = p[0][index]; p_r[1][index] = p[1][index]; } /**Drag a control point and adjust the other, dependent one, in a symmetric way or not.*/ protected void dragControlPoint(int index, int x_d, int y_d, double[][] p_dragged, double[][] p_adjusted, boolean symmetric) { //measure hypothenusa: from p to p control double hypothenusa; if (symmetric) { //make both points be dragged in parallel, the same distance hypothenusa = distance(p[0][index], p[1][index], p_dragged[0][index], p_dragged[1][index]); } else { //make each point be dragged with its own distance hypothenusa = distance(p[0][index], p[1][index], p_adjusted[0][index], p_adjusted[1][index]); } //measure angle: use the point being dragged double angle = Math.atan2(p_dragged[0][index] - p[0][index], p_dragged[1][index] - p[1][index]) + Math.PI; //apply p_dragged[0][index] = x_d; p_dragged[1][index] = y_d; p_adjusted[0][index] = p[0][index] + hypothenusa * Math.sin(angle); // it's sin and not cos because of stupid Math.atan2 way of delivering angles p_adjusted[1][index] = p[1][index] + hypothenusa * Math.cos(angle); } static private double getFirstWidth() { if (null == Display.getFront()) return 1; if (-1 != last_radius) return last_radius; return 10 / Display.getFront().getCanvas().getMagnification(); // 10 pixels in the screen } /**Add a point either at the end or between two existing points, with accuracy depending on magnification. The width of the new point is that of the closest point after which it is inserted.*/ synchronized protected int addPoint(int x_p, int y_p, double magnification, double bezier_finess, long layer_id) { if (-1 == n_points) setupForDisplay(); //reload //lookup closest interpolated point and then get the closest clicked point to it int index = findClosestPoint(x_p, y_p, magnification, bezier_finess); //check array size if (p[0].length == n_points) { enlargeArrays(); } //decide: if (0 == n_points || 1 == n_points || index + 1 == n_points) { //append at the end p[0][n_points] = p_l[0][n_points] = p_r[0][n_points] = x_p; p[1][n_points] = p_l[1][n_points] = p_r[1][n_points] = y_p; p_layer[n_points] = layer_id; p_width[n_points] = (0 == n_points ? Pipe.getFirstWidth() : p_width[n_points -1]); // either 1.0 or the same as the last point index = n_points; } else if (-1 == index) { // decide whether to append at the end or prepend at the beginning // compute distance in the 3D space to the first and last points final Calibration cal = layer_set.getCalibration(); final double lz = layer_set.getLayer(layer_id).getZ(); final double p0z =layer_set.getLayer(p_layer[0]).getZ(); final double pNz =layer_set.getLayer(p_layer[n_points -1]).getZ(); double sqdist0 = (p[0][0] - x_p) * (p[0][0] - x_p) * cal.pixelWidth * cal.pixelWidth + (p[1][0] - y_p) * (p[1][0] - y_p) * cal.pixelHeight * cal.pixelHeight + (lz - p0z) * (lz - p0z) * cal.pixelWidth * cal.pixelWidth; double sqdistN = (p[0][n_points-1] - x_p) * (p[0][n_points-1] - x_p) * cal.pixelWidth * cal.pixelWidth + (p[1][n_points-1] - y_p) * (p[1][n_points-1] - y_p) * cal.pixelHeight * cal.pixelHeight + (lz - pNz) * (lz - pNz) * cal.pixelWidth * cal.pixelWidth; if (sqdistN < sqdist0) { //append at the end p[0][n_points] = p_l[0][n_points] = p_r[0][n_points] = x_p; p[1][n_points] = p_l[1][n_points] = p_r[1][n_points] = y_p; p_layer[n_points] = layer_id; p_width[n_points] = p_width[n_points -1]; index = n_points; } else { // prepend at the beginning for (int i=n_points-1; i>-1; i--) { p[0][i+1] = p[0][i]; p[1][i+1] = p[1][i]; p_l[0][i+1] = p_l[0][i]; p_l[1][i+1] = p_l[1][i]; p_r[0][i+1] = p_r[0][i]; p_r[1][i+1] = p_r[1][i]; p_width[i+1] = p_width[i]; p_layer[i+1] = p_layer[i]; } p[0][0] = p_l[0][0] = p_r[0][0] = x_p; p[1][0] = p_l[1][0] = p_r[1][0] = y_p; p_width[0] = p_width[1]; p_layer[0] = layer_id; index = 0; } //debug: I miss gdb/ddd ! //Utils.log("p_width.length = " + p_width.length + " || n_points = " + n_points + " || p[0].length = " + p[0].length); } else { //insert at index: /* Utils.log(" p length = " + p[0].length + "\np_l length = " + p_l[0].length + "\np_r length = " + p_r[0].length + "\np_layer len= " + p_layer.length); */ index++; //so it is added after the closest point; // 1 - copy second half of array int sh_length = n_points -index; double[][] p_copy = new double[2][sh_length]; double[][] p_l_copy = new double[2][sh_length]; double[][] p_r_copy = new double[2][sh_length]; long[] p_layer_copy = new long[sh_length]; double[] p_width_copy = new double[sh_length]; System.arraycopy(p[0], index, p_copy[0], 0, sh_length); System.arraycopy(p[1], index, p_copy[1], 0, sh_length); System.arraycopy(p_l[0], index, p_l_copy[0], 0, sh_length); System.arraycopy(p_l[1], index, p_l_copy[1], 0, sh_length); System.arraycopy(p_r[0], index, p_r_copy[0], 0, sh_length); System.arraycopy(p_r[1], index, p_r_copy[1], 0, sh_length); //Utils.log2("index=" + index + " sh_length=" + sh_length + " p_layer.length=" + p_layer.length + " p_layer_copy.length=" + p_layer_copy.length + " p_copy[0].length=" + p_copy[0].length); System.arraycopy(p_layer, index, p_layer_copy, 0, sh_length); System.arraycopy(p_width, index, p_width_copy, 0, sh_length); // 2 - insert value into 'p' (the two control arrays get the same value) p[0][index] = p_l[0][index] = p_r[0][index] = x_p; p[1][index] = p_l[1][index] = p_r[1][index] = y_p; p_layer[index] = layer_id; p_width[index] = p_width[index-1]; // -1 because the index has been increased by 1 above // 3 - copy second half into the array System.arraycopy(p_copy[0], 0, p[0], index+1, sh_length); System.arraycopy(p_copy[1], 0, p[1], index+1, sh_length); System.arraycopy(p_l_copy[0], 0, p_l[0], index+1, sh_length); System.arraycopy(p_l_copy[1], 0, p_l[1], index+1, sh_length); System.arraycopy(p_r_copy[0], 0, p_r[0], index+1, sh_length); System.arraycopy(p_r_copy[1], 0, p_r[1], index+1, sh_length); System.arraycopy(p_layer_copy, 0, p_layer, index+1, sh_length); System.arraycopy(p_width_copy, 0, p_width, index+1, sh_length); } //add one up this.n_points++; return index; } /**Find the closest point to an interpolated point with precision depending upon magnification.*/ synchronized protected int findClosestPoint(int x_p, int y_p, double magnification, double bezier_finess) { int index = -1; double distance_sq = Double.MAX_VALUE; double distance_sq_i; double max = 12.0D / magnification; max = max * max; //squaring it for (int i=0; i<p_i[0].length; i++) { //see which point is closer (there's no need to calculate the distance by multiplying squares and so on). distance_sq_i = (p_i[0][i] - x_p)*(p_i[0][i] - x_p) + (p_i[1][i] - y_p)*(p_i[1][i] - y_p); if (distance_sq_i < max && distance_sq_i < distance_sq) { index = i; distance_sq = distance_sq_i; } } if (-1 != index) { int index_found = (int)Math.round((double)index * bezier_finess); // correct to be always the one after: count the number of points before reaching the next point if (index < (index_found / bezier_finess)) { index_found--; } index = index_found; // allow only when the closest index is visible in the current layer // handled at mousePressed now//if (Display.getFrontLayer(this.project).getId() != p_layer[index]) return -1; } return index; } synchronized protected void generateInterpolatedPoints(double bezier_finess) { if (0 == n_points) { return; } int n = n_points; // case there's only one point if (1 == n_points) { p_i = new double[2][1]; p_i[0][0] = p[0][0]; p_i[1][0] = p[1][0]; p_width_i = new double[1]; p_width_i[0] = p_width[0]; return; } // case there's more: interpolate! p_i = new double[2][(int)(n * (1.0D/bezier_finess))]; p_width_i = new double[p_i[0].length]; double t, f0, f1, f2, f3; int next = 0; for (int i=0; i<n-1; i++) { for (t=0.0D; t<1.0D; t += bezier_finess) { f0 = (1-t)*(1-t)*(1-t); f1 = 3*t*(1-t)*(1-t); f2 = 3*t*t*(1-t); f3 = t*t*t; p_i[0][next] = f0*p[0][i] + f1*p_r[0][i] + f2*p_l[0][i+1] + f3*p[0][i+1]; p_i[1][next] = f0*p[1][i] + f1*p_r[1][i] + f2*p_l[1][i+1] + f3*p[1][i+1]; p_width_i[next] = p_width[i]*(1-t) + p_width[i+1]*t; next++; //enlarge if needed (when bezier_finess is not 0.05, it's difficult to predict because of int loss of precision. if (p_i[0].length == next) { double[][] p_i_copy = new double[2][p_i[0].length + 5]; double[] p_width_i_copy = new double[p_width_i.length + 5]; System.arraycopy(p_i[0], 0, p_i_copy[0], 0, p_i[0].length); System.arraycopy(p_i[1], 0, p_i_copy[1], 0, p_i[1].length); System.arraycopy(p_width_i, 0, p_width_i_copy, 0, p_width_i.length); p_i = p_i_copy; p_width_i = p_width_i_copy; } } } // add the last point if (p_i[0].length == next) { double[][] p_i_copy = new double[2][p_i[0].length + 1]; double[] p_width_i_copy = new double[p_width_i.length + 1]; System.arraycopy(p_i[0], 0, p_i_copy[0], 0, p_i[0].length); System.arraycopy(p_i[1], 0, p_i_copy[1], 0, p_i[1].length); System.arraycopy(p_width_i, 0, p_width_i_copy, 0, p_width_i.length); p_i = p_i_copy; p_width_i = p_width_i_copy; } p_i[0][next] = p[0][n_points-1]; p_i[1][next] = p[1][n_points-1]; p_width_i[next] = p_width[n_points-1]; next++; if (p_i[0].length != next) { // 'next' works as a length here //resize back double[][] p_i_copy = new double[2][next]; double[] p_width_i_copy = new double[next]; System.arraycopy(p_i[0], 0, p_i_copy[0], 0, next); System.arraycopy(p_i[1], 0, p_i_copy[1], 0, next); System.arraycopy(p_width_i, 0, p_width_i_copy, 0, next); p_i = p_i_copy; p_width_i = p_width_i_copy; } } // synchronizing to protect n_points ... need to wrap it in a lock public void paint(final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer) { if (0 == n_points) return; if (-1 == n_points) { // load points from the database setupForDisplay(); } //arrange transparency Composite original_composite = null; if (alpha != 1.0f) { original_composite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } final boolean no_color_cues = "true".equals(project.getProperty("no_color_cues")); final long layer_id = active_layer.getId(); if (active) { // draw/fill points final int oval_radius = (int)Math.ceil(4 / magnification); final int oval_corr = (int)Math.ceil(3 / magnification); for (int j=0; j<n_points; j++) { //TODO there is room for optimization, operations are being done twice or 3 times; BUT is the creation of new variables as costly as the calculations? I have no idea. if (layer_id != p_layer[j]) continue; //draw big ovals at backbone points DisplayCanvas.drawHandle(g, (int)p[0][j], (int)p[1][j], magnification); g.setColor(color); //fill small ovals at control points g.fillOval((int)p_l[0][j] -oval_corr, (int)p_l[1][j] -oval_corr, oval_radius, oval_radius); g.fillOval((int)p_r[0][j] -oval_corr, (int)p_r[1][j] -oval_corr, oval_radius, oval_radius); //draw lines between backbone and control points g.drawLine((int)p[0][j], (int)p[1][j], (int)p_l[0][j], (int)p_l[1][j]); g.drawLine((int)p[0][j], (int)p[1][j], (int)p_r[0][j], (int)p_r[1][j]); // label the first point distinctively: if (0 == j) { Composite comp = g.getComposite(); - g.setXORMode(Color.white); + g.setColor(Color.white); + g.setXORMode(Color.green); g.drawString("1", (int)(p[0][0] + (4.0 / magnification)), (int)p[1][0]); // displaced 4 screen pixels to the right g.setComposite(comp); } } } // paint the tube in 2D: if (n_points > 1 && p_i[0].length > 1) { // need the second check for repaints that happen before generating the interpolated points. double angle = 0; double a0 = Math.toRadians(0); double a90 = Math.toRadians(90); double a180 = Math.toRadians(180); double a270 = Math.toRadians(270); final int n = p_i[0].length; final double[] r_side_x = new double[n]; final double[] r_side_y = new double[n]; final double[] l_side_x = new double[n]; final double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; final double z_current = active_layer.getZ(); if (no_color_cues) { // paint a tiny bit where it should! g.setColor(this.color); } for (int j=0; j<n_points; j++) { // at least looping through 2 points, as guaranteed by the preconditions checking if (no_color_cues) { if (layer_id == p_layer[j]) { // paint normally } else { // else if crossed the current layer, paint segment as well if (0 == j) continue; double z1 = layer_set.getLayer(p_layer[j-1]).getZ(); double z2 = layer_set.getLayer(p_layer[j]).getZ(); if ( (z1 < z_current && z_current < z2) || (z2 < z_current && z_current < z1) ) { // paint normally, in this pipe's color } else { continue; } } } else { double z = layer_set.getLayer(p_layer[j]).getZ(); if (z < z_current) g.setColor(Color.red); else if (z == z_current) g.setColor(this.color); else g.setColor(Color.blue); } int fi = 0; int la = j * 20 -1; if (0 != j) fi = (j * 20) - 10; // 10 is half a segment if (n_points -1 != j) la += 10; // same //= j * 20 + 9; if (la >= r_side_x.length) la = r_side_x.length-2; // quick fix. -2 so that the k+1 below can work if (fi > la) fi = la; try { for (int k=fi; k<=la; k++) { g.drawLine((int)r_side_x[k], (int)r_side_y[k], (int)r_side_x[k+1], (int)r_side_y[k+1]); g.drawLine((int)l_side_x[k], (int)l_side_y[k], (int)l_side_x[k+1], (int)l_side_y[k+1]); } } catch (Exception ee) { Utils.log2("Pipe paint failed with: fi=" + fi + " la=" + la + " n_points=" + n_points + " r_side_x.length=" + r_side_x.length); // WARNING still something is wrong with the synchronization over the arrays ... despite this error being patched with the line above: // if (la >= r_side_x.length) r_side_x.length-2; // quick fix // // ADDING the synchronized keyword to many methods involving n_points did not fix it; neither to crop arrays and get the new n_points from the getTransformedData() returned p array. } } } //Transparency: fix alpha composite back to original. if (null != original_composite) { g.setComposite(original_composite); } } public void keyPressed(KeyEvent ke) { //Utils.log2("Pipe.keyPressed not implemented."); } /**Helper vars for mouse events. It's safe to have them static since only one Pipe will be edited at a time.*/ static private int index, index_l, index_r; static private boolean is_new_point = false; public void mousePressed(MouseEvent me, int x_p, int y_p, double mag) { // transform the x_p, y_p to the local coordinates if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_p = (int)po.x; y_p = (int)po.y; } final int tool = ProjectToolbar.getToolId(); if (ProjectToolbar.PEN == tool) { if (Utils.isControlDown(me) && me.isShiftDown()) { index = Displayable.findNearestPoint(p, n_points, x_p, y_p); } else { index = findPoint(p, x_p, y_p, mag); } if (-1 != index) { if (Utils.isControlDown(me) && me.isShiftDown() && p_layer[index] == Display.getFrontLayer(this.project).getId()) { //delete point removePoint(index); index = index_r = index_l = -1; repaint(false); return; } // Make the radius for newly added point that of the last added last_radius = p_width[index]; // if (me.isAltDown()) { resetControlPoints(index); return; } } // find if click is on a left control point index_l = findPoint(p_l, x_p, y_p, mag); index_r = -1; // if not, then try on the set of right control points if (-1 == index_l) { index_r = findPoint(p_r, x_p, y_p, mag); } long layer_id = Display.getFrontLayer(this.project).getId(); if (-1 != index && layer_id != p_layer[index]) index = -1; // disable! else if (-1 != index_l && layer_id != p_layer[index_l]) index_l = -1; else if (-1 != index_r && layer_id != p_layer[index_r]) index_r = -1; //if no conditions are met, attempt to add point else if (-1 == index && -1 == index_l && -1 == index_r && !me.isShiftDown() && !me.isAltDown()) { //add a new point and assign its index to the left control point, so it can be dragged right away. This is copying the way Karbon does for drawing Bezier curves, which is the contrary to Adobe's way, but which I find more useful. index_l = addPoint(x_p, y_p, mag, 0.05, layer_id); is_new_point = true; if (0 == index_l) { //1 == n_points) //for the very first point, drag the right control point, not the left. index_r = index_l; index_l = -1; } else { generateInterpolatedPoints(0.05); } repaint(false); return; } } } public void mouseDragged(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_d_old, int y_d_old) { // transform to the local coordinates if (!this.at.isIdentity()) { final Point2D.Double p = inverseTransformPoint(x_p, y_p); x_p = (int)p.x; y_p = (int)p.y; final Point2D.Double pd = inverseTransformPoint(x_d, y_d); x_d = (int)pd.x; y_d = (int)pd.y; final Point2D.Double pdo = inverseTransformPoint(x_d_old, y_d_old); x_d_old = (int)pdo.x; y_d_old = (int)pdo.y; } final int tool = ProjectToolbar.getToolId(); if (ProjectToolbar.PEN == tool) { //if a point in the backbone is found, then: if (-1 != index) { if (!me.isAltDown() && !me.isShiftDown()) { dragPoint(index, x_d - x_d_old, y_d - y_d_old); } else if (me.isShiftDown()) { // resize radius p_width[index] = Math.sqrt((x_d - p[0][index])*(x_d - p[0][index]) + (y_d - p[1][index])*(y_d - p[1][index])); last_radius = p_width[index]; Utils.showStatus("radius: " + p_width[index], false); } else { //TODO in linux the alt+click is stolen by the KDE window manager but then the middle-click works as if it was the alt+click. Weird! //drag both control points symmetrically dragControlPoint(index, x_d, y_d, p_l, p_r, true); } generateInterpolatedPoints(0.05); repaint(false); return; } //if a control point is found, then drag it, adjusting the other control point non-symmetrically if (-1 != index_r) { dragControlPoint(index_r, x_d, y_d, p_r, p_l, is_new_point); //((index_r != n_points-1)?false:true)); //last point gets its 2 control points dragged symetrically generateInterpolatedPoints(0.05); repaint(false); return; } if (-1 != index_l) { dragControlPoint(index_l, x_d, y_d, p_l, p_r, is_new_point); //((index_l != n_points-1)?false:true)); //last point gets its 2 control points dragged symetrically generateInterpolatedPoints(0.05); repaint(false); return; } } } public void mouseReleased(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_r, int y_r) { final int tool = ProjectToolbar.getToolId(); if (ProjectToolbar.PEN == tool) { //generate interpolated points generateInterpolatedPoints(0.05); repaint(); //needed at least for the removePoint } //update points in database if there was any change if (-1 != index || -1 != index_r || -1 != index_l) { //updateInDatabase("position"); if (is_new_point) { // update all points, since the index may have changed updateInDatabase("points"); } else if (-1 != index && index != n_points) { //second condition happens when the last point has been removed updateInDatabase(getUpdatePointForSQL(index)); } else if (-1 != index_r) { updateInDatabase(getUpdateRightControlPointForSQL(index_r)); } else if (-1 != index_l) { updateInDatabase(getUpdateLeftControlPointForSQL(index_l)); } else if (index != n_points) { // don't do it when the last point is removed // update all updateInDatabase("points"); } updateInDatabase("dimensions"); } else if (x_r != x_p || y_r != y_p) { updateInDatabase("dimensions"); } //Display.repaint(layer, this, 5); // the entire Displayable object repaint(true); // reset is_new_point = false; index = index_r = index_l = -1; } synchronized protected void calculateBoundingBox(final boolean adjust_position) { double min_x = Double.MAX_VALUE; double min_y = Double.MAX_VALUE; double max_x = 0.0D; double max_y = 0.0D; if (0 == n_points) { this.width = this.height = 0; layer_set.updateBucket(this); return; } // get perimeter of the tube, without the transform final Polygon pol = Pipe.getRawPerimeter(p_i, p_width_i); if (null != pol && 0 != pol.npoints) { // check the tube for (int i=0; i<pol.npoints; i++) { if (pol.xpoints[i] < min_x) min_x = pol.xpoints[i]; if (pol.ypoints[i] < min_y) min_y = pol.ypoints[i]; if (pol.xpoints[i] > max_x) max_x = pol.xpoints[i]; if (pol.ypoints[i] > max_y) max_y = pol.ypoints[i]; } } // check the control points for (int i=0; i<n_points; i++) { if (p_l[0][i] < min_x) min_x = p_l[0][i]; if (p_r[0][i] < min_x) min_x = p_r[0][i]; if (p_l[1][i] < min_y) min_y = p_l[1][i]; if (p_r[1][i] < min_y) min_y = p_r[1][i]; if (p_l[0][i] > max_x) max_x = p_l[0][i]; if (p_r[0][i] > max_x) max_x = p_r[0][i]; if (p_l[1][i] > max_y) max_y = p_l[1][i]; if (p_r[1][i] > max_y) max_y = p_r[1][i]; } this.width = max_x - min_x; this.height = max_y - min_y; if (adjust_position) { // now readjust points to make min_x,min_y be the x,y for (int i=0; i<n_points; i++) { p[0][i] -= min_x; p[1][i] -= min_y; p_l[0][i] -= min_x; p_l[1][i] -= min_y; p_r[0][i] -= min_x; p_r[1][i] -= min_y; } for (int i=0; i<p_i[0].length; i++) { p_i[0][i] -= min_x; p_i[1][i] -= min_y; } this.at.translate(min_x, min_y); // not using super.translate(...) because a preConcatenation is not needed; here we deal with the data. updateInDatabase("transform"); } updateInDatabase("dimensions"); layer_set.updateBucket(this); } /**Release all memory resources taken by this object.*/ synchronized public void destroy() { super.destroy(); p = null; p_l = null; p_r = null; p_layer = null; p_width = null; p_i = null; p_width_i = null; } /**Release memory resources used by this object: namely the arrays of points, which can be reloaded with a call to setupForDisplay()*/ synchronized public void flush() { p = null; p_l = null; p_r = null; p_i = null; p_width = null; p_layer = null; n_points = -1; // flag that points exist but are not loaded } public void repaint() { repaint(true); } /**Repaints in the given ImageCanvas only the area corresponding to the bounding box of this Pipe. */ public void repaint(boolean repaint_navigator) { //TODO: this could be further optimized to repaint the bounding box of the last modified segments, i.e. the previous and next set of interpolated points of any given backbone point. This would be trivial if each segment of the Bezier curve was an object. Rectangle box = getBoundingBox(null); calculateBoundingBox(true); box.add(getBoundingBox(null)); Display.repaint(layer_set, this, box, 5, repaint_navigator); } /**Make this object ready to be painted.*/ synchronized private void setupForDisplay() { // load points if (null == p || null == p_l || null == p_r) { ArrayList al = project.getLoader().fetchPipePoints(id); n_points = al.size(); p = new double[2][n_points]; p_l = new double[2][n_points]; p_r = new double[2][n_points]; p_layer = new long[n_points]; p_width = new double[n_points]; Iterator it = al.iterator(); int i = 0; while (it.hasNext()) { Object[] ob = (Object[])it.next(); p[0][i] = ((Double)ob[0]).doubleValue(); p[1][i] = ((Double)ob[1]).doubleValue(); p_r[0][i] = ((Double)ob[2]).doubleValue(); p_r[1][i] = ((Double)ob[3]).doubleValue(); p_l[0][i] = ((Double)ob[4]).doubleValue(); p_l[1][i] = ((Double)ob[5]).doubleValue(); p_width[i] = ((Double)ob[6]).doubleValue(); p_layer[i] = ((Long)ob[7]).longValue(); i++; } // recreate interpolated points generateInterpolatedPoints(0.05); //TODO adjust this or make it read the value from the Project perhaps. } } static private final Polygon getRawPerimeter(final double[][] p_i, final double[] p_width_i) { final int n = p_i[0].length; // the number of interpolated points if (n < 2) return null; double angle = 0; final double a0 = Math.toRadians(0); final double a90 = Math.toRadians(90); final double a180 = Math.toRadians(180); final double a270 = Math.toRadians(270); double[] r_side_x = new double[n]; double[] r_side_y = new double[n]; double[] l_side_x = new double[n]; double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } // last point angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; int[] pol_x = new int[n * 2]; int[] pol_y = new int[n * 2]; for (int j=0; j<n; j++) { pol_x[j] = (int)r_side_x[j]; pol_y[j] = (int)r_side_y[j]; pol_x[n + j] = (int)l_side_x[m -j]; pol_y[n + j] = (int)l_side_y[m -j]; } return new Polygon(pol_x, pol_y, pol_x.length); } /** The exact perimeter of this pipe, in integer precision. */ synchronized public Polygon getPerimeter() { if (null == p_i || p_i[0].length < 2) return new Polygon(); // meaning: if there aren't any interpolated points // local pointers, since they may be transformed int n_points = this.n_points; //double[][] p = this.p; //double[][] p_r = this.p_r; //double[][] p_l = this.p_l; double[][] p_i = this.p_i; //double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); //p = (double[][])ob[0]; n_points = p[0].length; //p_l = (double[][])ob[1]; //p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; //p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } return Pipe.getRawPerimeter(p_i, p_width_i); } /** Writes the data of this object as a Pipe object in the .shapes file represented by the 'data' StringBuffer. */ synchronized public void toShapesFile(StringBuffer data, String group, String color, double z_scale) { if (-1 == n_points) setupForDisplay(); // reload final char l = '\n'; // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[] p_width = this.p_width; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_width = (double[])ob[4]; } data.append("type=pipe").append(l) .append("name=").append(project.getMeaningfulTitle(this)).append(l) .append("group=").append(group).append(l) .append("color=").append(color).append(l) .append("supergroup=").append("null").append(l) .append("supercolor=").append("null").append(l) ; for (int i=0; i<n_points; i++) { data.append("p x=").append(p[0][i]).append(l) .append("p y=").append(p[1][i]).append(l) .append("p_r x=").append(p_r[0][i]).append(l) .append("p_r y=").append(p_r[1][i]).append(l) .append("p_l x=").append(p_l[0][i]).append(l) .append("p_l y=").append(p_l[1][i]).append(l) .append("z=").append(layer_set.getLayer(p_layer[i]).getZ() * z_scale).append(l) .append("width=").append(p_width[i]).append(l) ; } } /** Return the list of query statements needed to insert all the points in the database. */ synchronized public String[] getPointsForSQL() { String[] sql = new String[n_points]; for (int i=0; i<n_points; i++) { StringBuffer sb = new StringBuffer("INSERT INTO ab_pipe_points (pipe_id, index, x, y, x_r, y_r, x_l, y_l, width, layer_id) VALUES ("); sb.append(this.id).append(",") .append(i).append(",") .append(p[0][i]).append(",") .append(p[1][i]).append(",") .append(p_r[0][i]).append(",") .append(p_r[1][i]).append(",") .append(p_l[0][i]).append(",") .append(p_l[1][i]).append(",") .append(p_width[i]).append(",") .append(p_layer[i]) .append(")"); ; //end sql[i] = sb.toString(); } return sql; } synchronized public String getUpdatePointForSQL(int index) { if (index < 0 || index > n_points-1) return null; StringBuffer sb = new StringBuffer("UPDATE ab_pipe_points SET "); sb.append("x=").append(p[0][index]) .append(", y=").append(p[1][index]) .append(", x_r=").append(p_r[0][index]) .append(", y_r=").append(p_r[1][index]) .append(", x_l=").append(p_l[0][index]) .append(", y_l=").append(p_l[1][index]) .append(", width=").append(p_width[index]) .append(", layer_id=").append(p_layer[index]) .append(" WHERE pipe_id=").append(this.id) .append(" AND index=").append(index) ; //end return sb.toString(); } String getUpdateLeftControlPointForSQL(int index) { if (index < 0 || index > n_points-1) return null; StringBuffer sb = new StringBuffer("UPDATE ab_pipe_points SET "); sb.append("x_l=").append(p_l[0][index]) .append(", y_l=").append(p_l[1][index]) .append(" WHERE pipe_id=").append(this.id) .append(" AND index=").append(index) ; //end return sb.toString(); } String getUpdateRightControlPointForSQL(int index) { if (index < 0 || index > n_points-1) return null; StringBuffer sb = new StringBuffer("UPDATE ab_pipe_points SET "); sb.append("x_r=").append(p_r[0][index]) .append(", y_r=").append(p_r[1][index]) .append(" WHERE pipe_id=").append(this.id) .append(" AND index=").append(index) ; //end return sb.toString(); } public boolean isDeletable() { return 0 == n_points; } /** The number of clicked, backbone points in this pipe. */ public int length() { if (-1 == n_points) setupForDisplay(); return n_points; } /** Test whether the Pipe contains the given point at the given layer. What it does: generates subpolygons that are present in the given layer, and tests whether the point is contained in any of them. */ public boolean contains(final Layer layer, int x, int y) { if (-1 == n_points) setupForDisplay(); // reload points if (0 == n_points) return false; // make x,y local final Point2D.Double po = inverseTransformPoint(x, y); x = (int)po.x; y = (int)po.y; if (1 == n_points) { if (Math.abs(p[0][0] - x) < 3 && Math.abs(p[1][0] - y) < 3) return true; // error in clicked precision of 3 pixels else return false; } final boolean no_color_cues = "true".equals(project.getProperty("no_color_cues")); double angle = 0; double a0 = Math.toRadians(0); double a90 = Math.toRadians(90); double a180 = Math.toRadians(180); double a270 = Math.toRadians(270); int n = p_i[0].length; // the number of interpolated points final double[] r_side_x = new double[n]; final double[] r_side_y = new double[n]; final double[] l_side_x = new double[n]; final double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); // side points, displaced by this.x, this.y r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } // last point angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); // side points, displaced by this.x, this.y r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; final long layer_id = layer.getId(); final double z_current = layer.getZ(); int first = 0; // the first backbone point in the subpolygon present in the layer int last = 0; // the last backbone point in the subpolygon present in the layer boolean add_pol = false; for (int j=0; j<n_points; j++) { // at least looping through 2 points, as guaranteed by the preconditions checking if (!no_color_cues && layer_id != p_layer[j]) { first = j + 1; // perhaps next, not this j continue; } last = j; // if j is last point, or the next point won't be in the same layer: if (j == n_points -1 || layer_id != p_layer[j+1]) { add_pol = true; } int fi=0, la=0; if (no_color_cues) { // else if crossed the current layer, check segment as well if (0 == j) continue; first = j -1; final double z1 = layer_set.getLayer(p_layer[j-1]).getZ(); final double z2 = layer_set.getLayer(p_layer[j]).getZ(); // 20 points is the length of interpolated points between any two backbone bezier 'j' points. // 10 points is half that. // // Painting with cues paints the points on the layer padded 10 points to before and after, and when no points are in the layer, then just some padded area in between. // // When approaching from below or from above, or when leaving torwards below or towards above, the segment to check is only half the length, as painted. if (z1 == z_current && z_current == z2) { add_pol = true; fi = ((j-1) * 20) - 10; la = ( j * 20) + 10; } else if ( (z1 < z_current && z_current == z2) || (z1 > z_current && z_current == z2) ) { add_pol = true; fi = ((j-1) * 20) + 10; la = ( j * 20) + 10; } else if ( (z1 == z_current && z_current < z2) || (z1 == z_current && z_current > z2) ) { add_pol = true; fi = ((j-1) * 20) - 10; la = ( j * 20) - 10; } else if ( (z1 < z_current && z_current < z2) || (z1 > z_current && z_current > z2) ) { add_pol = true; // crossing by without a point: short polygons fi = ((j-1) * 20) + 10; la = ( j * 20) - 10; } else { //add_pol = false; continue; } // correct ends if (0 == j-1) fi = 0; if (n_points-1 == j) la = n_points * 20; } if (add_pol) { // compute sub polygon if (!no_color_cues) { fi = 0; la = last * 20 -1; if (0 != first) fi = (first * 20) - 10; // 10 is half a segment if (n_points -1 != last) la += 10; // same //= last * 20 + 9; } else { if (fi < 0) fi = 0; } if (la >= r_side_x.length) la = r_side_x.length-1; // quick fix final int length = la - fi + 1; // +1 because fi and la are indices final int [] pol_x = new int[length * 2]; final int [] pol_y = new int[length * 2]; for (int k=0, g=fi; g<=la; g++, k++) { pol_x[k] = (int)r_side_x[g]; pol_y[k] = (int)r_side_y[g]; pol_x[length + k] = (int)l_side_x[la - k]; pol_y[length + k] = (int)l_side_y[la - k]; } final Polygon pol = new Polygon(pol_x, pol_y, pol_x.length); if (pol.contains(x, y)) { //Utils.log2("first, last : " + first + ", " + last); //showShape(pol); return true; } // reset first = j + 1; add_pol = false; } } return false; } /** Get the perimeter of all parts that show in the given layer (as defined by its Z). Returns null if none found. */ private Polygon[] getSubPerimeters(final Layer layer) { if (n_points <= 1) return null; // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } double angle = 0; double a0 = Math.toRadians(0); double a90 = Math.toRadians(90); double a180 = Math.toRadians(180); double a270 = Math.toRadians(270); int n = p_i[0].length; // the number of interpolated points double[] r_side_x = new double[n]; double[] r_side_y = new double[n]; double[] l_side_x = new double[n]; double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); // side points r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } // last point angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); // side points, displaced by this.x, this.y r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; final long layer_id = layer.getId(); //double z_given = layer.getZ(); //double z = 0; int first = 0; // the first backbone point in the subpolygon present in the layer int last = 0; // the last backbone point in the subpolygon present in the layer boolean add_pol = false; final ArrayList al = new ArrayList(); for (int j=0; j<n_points; j++) { if (layer_id != p_layer[j]) { first = j + 1; // perhaps next, not this j continue; } last = j; // if j is last point, or the next point won't be in the same layer: if (j == n_points -1 || layer_id != p_layer[j+1]) { add_pol = true; } if (add_pol) { // compute sub polygon int fi = 0; int la = last * 20 -1; if (0 != first) fi = (first * 20) - 10; // 10 is half a segment if (n_points -1 != last) la += 10; // same //= last * 20 + 9; int length = la - fi + 1; // +1 because fi and la are indexes int [] pol_x = new int[length * 2]; int [] pol_y = new int[length * 2]; for (int k=0, g=fi; g<=la; g++, k++) { pol_x[k] = (int)r_side_x[g]; pol_y[k] = (int)r_side_y[g]; pol_x[length + k] = (int)l_side_x[la - k]; pol_y[length + k] = (int)l_side_y[la - k]; } al.add(new Polygon(pol_x, pol_y, pol_x.length)); // reset first = j + 1; add_pol = false; } } if (al.isEmpty()) return null; else { final Polygon[] pols = new Polygon[al.size()]; al.toArray(pols); return pols; } } // scan the Display and link Patch objects that lay under this Pipe's bounding box: public void linkPatches() { // TODO needs to check all layers!! // SHOULD check on every layer where there is a subperimeter. This method below will work only while the Display is not switching layer before deselecting this pipe (which calls linkPatches) // find the patches that don't lay under other profiles of this profile's linking group, and make sure they are unlinked. This will unlink any Patch objects under this Pipe: unlinkAll(Patch.class); HashSet hs = new HashSet(); for (int l=0; l<n_points; l++) { // avoid repeating the ones that have been done Long lo = new Long(p_layer[l]); // in blankets ... if (hs.contains(lo)) continue; else hs.add(lo); Layer layer = layer_set.getLayer(p_layer[l]); // this bounding box as in the current layer final Polygon[] perimeters = getSubPerimeters(layer); if (null == perimeters) continue; // catch all displayables of the current Layer final ArrayList al = layer.getDisplayables(Patch.class); // for each Patch, check if it underlays this profile's bounding box final Rectangle box = new Rectangle(); for (Iterator itd = al.iterator(); itd.hasNext(); ) { final Displayable displ = (Displayable)itd.next(); // stupid java, Polygon cannot test for intersection with another Polygon !! //if (perimeter.intersects(displ.getPerimeter())) // TODO do it yourself: check if a Displayable intersects another Displayable for (int i=0; i<perimeters.length; i++) { if (perimeters[i].intersects(displ.getBoundingBox(box))) { // Link the patch this.link(displ); break; // no need to check more perimeters } } } } } /** Returns the layer of lowest Z coordinate where this ZDisplayable has a point in, or the creation layer if no points yet. */ public Layer getFirstLayer() { if (0 == n_points) return this.layer; if (-1 == n_points) setupForDisplay(); //reload Layer la = this.layer; double z = Double.MAX_VALUE; for (int i=0; i<n_points; i++) { Layer layer = layer_set.getLayer(p_layer[i]); if (layer.getZ() < z) la = layer; } return la; } synchronized public void exportSVG(StringBuffer data, double z_scale, String indent) { String in = indent + "\t"; if (-1 == n_points) setupForDisplay(); // reload if (0 == n_points) return; String[] RGB = Utils.getHexRGBColor(color); final double[] a = new double[6]; at.getMatrix(a); data.append(indent).append("<path\n") .append(in).append("type=\"pipe\"\n") .append(in).append("id=\"").append(id).append("\"\n") .append(in).append("transform=\"matrix(").append(a[0]).append(',') .append(a[1]).append(',') .append(a[2]).append(',') .append(a[3]).append(',') .append(a[4]).append(',') .append(a[5]).append(")\"\n") .append(in).append("style=\"fill:none;stroke-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";stroke-width:1.0px;stroke-opacity:1.0\"\n") .append(in).append("d=\"M") ; for (int i=0; i<n_points-1; i++) { data.append(" ").append(p[0][i]).append(",").append(p[1][i]) .append(" C ").append(p_r[0][i]).append(",").append(p_r[1][i]) .append(" ").append(p_l[0][i+1]).append(",").append(p_l[1][i+1]) ; } data.append(" ").append(p[0][n_points-1]).append(',').append(p[1][n_points-1]); data.append("\"\n") .append(in).append("z=\"") ; for (int i=0; i<n_points; i++) { data.append(layer_set.getLayer(p_layer[i]).getZ() * z_scale).append(","); } data.append(in).append("\"\n"); data.append(in).append("p_width=\""); for (int i=0; i<n_points; i++) { data.append(p_width[i]).append(","); } data.append("\"\n") .append(in).append("links=\""); if (null != hs_linked && 0 != hs_linked.size()) { int ii = 0; int len = hs_linked.size(); for (Iterator it = hs_linked.iterator(); it.hasNext(); ) { Object ob = it.next(); data.append(((DBObject)ob).getId()); if (ii != len-1) data.append(","); ii++; } } data.append(indent).append("\"\n/>\n"); } /** Returns a [p_i[0].length][4] array, with x,y,z,radius on the second part. Not translated to x,y but local!*/ public double[][] getBackbone() { if (-1 == n_points) setupForDisplay(); // reload double[][] b = new double[p_i[0].length][4]; int ni = 20; // 1/0.05; int start = 0; for (int j=0; j<n_points -1; j++) { double z1 = layer_set.getLayer(p_layer[j]).getZ(); double z2 = layer_set.getLayer(p_layer[j+1]).getZ(); double depth = z2 - z1; double radius1 = p_width[j]; double radius2 = p_width[j+1]; double dif = radius2 - radius1; for (int i=start, k=0; i<start + ni; i++, k++) { b[i][0] = p_i[0][i]; b[i][1] = p_i[1][i]; b[i][2] = z1 + (k * depth) / (double)ni; b[i][3] = radius1 + (k * dif) / (double)ni; } start += ni; } // last point start = p_i[0].length-1; // recycling start b[start][0] = p[0][n_points-1]; b[start][1] = p[1][n_points-1]; b[start][2] = layer_set.getLayer(p_layer[n_points-1]).getZ(); b[start][3] = p_width[n_points-1]; return b; } /** x,y is the cursor position in offscreen coordinates. */ public void snapTo(int cx, int cy, int x_p, int y_p) { // WARNING: DisplayCanvas is locking at mouseDragged when the cursor is outside the DisplayCanvas Component, so this is useless or even harmful at the moment. if (-1 != index) { // #$#@$%#$%!!! TODO this doesn't work, although it *should*. The index_l and index_r work, and the mouseEntered coordinates are fine too. Plus it messes up the x,y position or something, for then on reload the pipe is streched or displaced (not clear). /* double dx = p_l[0][index] - p[0][index]; double dy = p_l[1][index] - p[1][index]; p_l[0][index] = cx + dx; p_l[1][index] = cy + dy; dx = p_r[0][index] - p[0][index]; dy = p_r[1][index] - p[1][index]; p_r[0][index] = cx + dx; p_r[1][index] = cy + dy; p[0][index] = cx; p[1][index] = cy; */ } else if (-1 != index_l) { p_l[0][index_l] = cx; p_l[1][index_l] = cy; } else if (-1 != index_r) { p_r[0][index_r] = cx; p_r[1][index_r] = cy; } else { // drag the whole pipe // CONCEPTUALLY WRONG, what happens when not dragging the pipe, on mouseEntered? Disaster! //drag(cx - x_p, cy - y_p); } } /** Exports data, the tag is not opened nor closed. */ synchronized public void exportXML(StringBuffer sb_body, String indent, Object any) { sb_body.append(indent).append("<t2_pipe\n"); String in = indent + "\t"; super.exportXML(sb_body, in, any); if (-1 == n_points) setupForDisplay(); // reload //if (0 == n_points) return; String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("style=\"fill:none;stroke-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";stroke-width:1.0px;stroke-opacity:1.0\"\n"); if (n_points > 0) { sb_body.append(in).append("d=\"M"); for (int i=0; i<n_points-1; i++) { sb_body.append(" ").append(p[0][i]).append(",").append(p[1][i]) .append(" C ").append(p_r[0][i]).append(",").append(p_r[1][i]) .append(" ").append(p_l[0][i+1]).append(",").append(p_l[1][i+1]) ; } sb_body.append(" ").append(p[0][n_points-1]).append(',').append(p[1][n_points-1]).append("\"\n"); sb_body.append(in).append("layer_ids=\""); // different from 'layer_id' in superclass for (int i=0; i<n_points; i++) { sb_body.append(p_layer[i]); if (n_points -1 != i) sb_body.append(","); } sb_body.append("\"\n"); sb_body.append(in).append("p_width=\""); for (int i=0; i<n_points; i++) { sb_body.append(p_width[i]); if (n_points -1 != i) sb_body.append(","); } sb_body.append("\"\n"); } sb_body.append(indent).append(">\n"); super.restXML(sb_body, in, any); sb_body.append(indent).append("</t2_pipe>\n"); } static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) { String type = "t2_pipe"; if (hs.contains(type)) return; hs.add(type); sb_header.append(indent).append("<!ELEMENT t2_pipe (").append(Displayable.commonDTDChildren()).append(")>\n"); Displayable.exportDTD(type, sb_header, hs, indent); sb_header.append(indent).append(TAG_ATTR1).append(type).append(" d").append(TAG_ATTR2) .append(indent).append(TAG_ATTR1).append(type).append(" p_width").append(TAG_ATTR2) ; } // TODO synchronized public double[][][] generateMesh(double scale) { if (-1 == n_points) setupForDisplay(); //reload if (0 == n_points) return null; // at any given segment (bezier curve defined by 4 points): // - resample to homogenize point distribution // - if z doesn't change, use no intermediate sections in the tube // - for each point: // - add the section as 12 points, by rotating a perpendicular vector around the direction vector // - if the point is the first one in the segment, use a direction vector averaged with the previous and the first in the segment (if it's not point 0, that is) Utils.log2("Pipe.generateMesh is not implemented yet."); // debug: return null; } /** Performs a deep copy of this object, without the links. */ synchronized public Displayable clone(final Project pr, final boolean copy_id) { final long nid = copy_id ? this.id : pr.getLoader().getNextId(); final Pipe copy = new Pipe(pr, nid, null != title ? title.toString() : null, width, height, alpha, this.visible, new Color(color.getRed(), color.getGreen(), color.getBlue()), this.locked, (AffineTransform)this.at.clone()); // The data: if (-1 == n_points) setupForDisplay(); // load data copy.n_points = n_points; copy.p = new double[][]{(double[])this.p[0].clone(), (double[])this.p[1].clone()}; copy.p_l = new double[][]{(double[])this.p_l[0].clone(), (double[])this.p_l[1].clone()}; copy.p_r = new double[][]{(double[])this.p_r[0].clone(), (double[])this.p_r[1].clone()}; copy.p_layer = (long[])this.p_layer.clone(); copy.p_width = (double[])this.p_width.clone(); copy.p_i = new double[][]{(double[])this.p_i[0].clone(), (double[])this.p_i[1].clone()}; copy.p_width_i = (double[])this.p_width_i.clone(); copy.addToDatabase(); return copy; } /** Calibrated. */ synchronized public List generateTriangles(double scale, int parallels, int resample) { if (n_points < 2) return null; // check minimum requirements. if (parallels < 3) parallels = 3; // double[][][] all_points = generateJoints(parallels, resample, layer_set.getCalibrationCopy()); return Pipe.generateTriangles(all_points, scale); } /** Accepts an arrays as that returned from methods generateJoints and makeTube: first dimension is the list of points, second dimension is the number of vertices defining the circular cross section of the tube, and third dimension is the x,y,z of each vertex. */ static public List generateTriangles(final double[][][] all_points, final double scale) { int n = all_points.length; final int parallels = all_points[0].length -1; List list = new ArrayList(); for (int i=0; i<n-1; i++) { //minus one since last is made with previous for (int j=0; j<parallels; j++) { //there are 12+12 triangles for each joint //it's up to 12+1 because first point is repeated at the end // first triangle in the quad list.add(new Point3f((float)(all_points[i][j][0] * scale), (float)(all_points[i][j][1] * scale), (float)(all_points[i][j][2] * scale))); list.add(new Point3f((float)(all_points[i][j+1][0] * scale), (float)(all_points[i][j+1][1] * scale), (float)(all_points[i][j+1][2] * scale))); list.add(new Point3f((float)(all_points[i+1][j][0] * scale), (float)(all_points[i+1][j][1] * scale), (float)(all_points[i+1][j][2] * scale))); // second triangle in the quad list.add(new Point3f((float)(all_points[i+1][j][0] * scale), (float)(all_points[i+1][j][1] * scale), (float)(all_points[i+1][j][2] * scale))); list.add(new Point3f((float)(all_points[i][j+1][0] * scale), (float)(all_points[i][j+1][1] * scale), (float)(all_points[i][j+1][2] * scale))); list.add(new Point3f((float)(all_points[i+1][j+1][0] * scale), (float)(all_points[i+1][j+1][1] * scale), (float)(all_points[i+1][j+1][2] * scale))); } } return list; } /** From my former program, A_3D_Editing.java and Pipe.java */ private double[][][] generateJoints(final int parallels, final int resample, final Calibration cal) { if (-1 == n_points) setupForDisplay(); // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } int n = p_i[0].length; final int mm = n_points; final double[] z_values = new double[n]; final int interval_points = n / (mm-1); double z_val = 0; double z_val_next = 0; double z_diff = 0; int c = 0; double delta = 0; for (int j=0; j<mm-1; j++) { z_val = layer_set.getLayer(p_layer[j]).getZ(); z_val_next = layer_set.getLayer(p_layer[j+1]).getZ(); z_diff = z_val_next - z_val; delta = z_diff/interval_points; z_values[c] = (0 == j ? z_val : z_values[c-1]) + delta; for (int k=1; k<interval_points; k++) { c++; z_values[c] = z_values[c-1] + delta; } c++; } //setting last point z_values[n-1] = layer_set.getLayer(p_layer[mm-1]).getZ(); return makeTube(p_i[0], p_i[1], z_values, p_width_i, resample, parallels, cal); } static public double[][][] makeTube(double[] px, double[] py, double[] pz, double[] p_width_i, final int resample, final int parallels, final Calibration cal) { int n = px.length; // Resampling to get a smoother pipe try { VectorString3D vs = new VectorString3D(px, py, pz, false); if (null != cal) { vs.calibrate(cal); for (int i=0; i<p_width_i.length; i++) p_width_i[i] *= cal.pixelWidth; } vs.addDependent(p_width_i); // Resample to the largest of the two: double avg_delta = vs.getAverageDelta(); double unit = null != cal ? 1 / cal.pixelWidth : 1; vs.resample(Math.max(avg_delta, unit) * resample); //vs.resample(vs.getAverageDelta() * resample); px = vs.getPoints(0); py = vs.getPoints(1); pz = vs.getPoints(2); p_width_i = vs.getDependent(0); //Utils.log("lengths: " + px.length + ", " + py.length + ", " + pz.length + ", " + p_width_i.length); n = vs.length(); } catch (Exception e) { IJError.print(e); } double[][][] all_points = new double[n+2][parallels+1][3]; int extra = 1; // this was zero when not doing capping for (int cap=0; cap<parallels+1; cap++) { all_points[0][cap][0] = px[0];//p_i[0][0]; //x all_points[0][cap][1] = py[0]; //p_i[1][0]; //y all_points[0][cap][2] = pz[0]; //z_values[0]; all_points[all_points.length-1][cap][0] = px[n-1]; //p_i[0][p_i[0].length-1]; all_points[all_points.length-1][cap][1] = py[n-1]; //p_i[1][p_i[0].length-1]; all_points[all_points.length-1][cap][2] = pz[n-1]; //z_values[z_values.length-1]; } double angle = 2*Math.PI/parallels; //Math.toRadians(30); Vector3 v3_P12; Vector3 v3_PR; Vector3[] circle = new Vector3[parallels+1]; double sinn, coss; int half_parallels = parallels/2; for (int i=0; i<n-1; i++) { //Utils.log2(i + " : " + px[i] + ", " + py[i] + ", " + pz[i]); //First vector: from one realpoint to the next //v3_P12 = new Vector3(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i], z_values[i+1] - z_values[i]); v3_P12 = new Vector3(px[i+1] - px[i], py[i+1] - py[i], pz[i+1] - pz[i]); //Second vector: ortogonal to v3_P12, made by cross product between v3_P12 and a modifies v3_P12 (either y or z set to 0) //checking that v3_P12 has not z set to 0, in which case it woundn´t be different and then the cross product not give an ortogonal vector as output //chosen random vector: the same vector, but with x = 0; /* matrix: 1 1 1 1 1 1 1 1 1 1 1 1 v1 v2 v3 P12[0] P12[1] P12[2] P12[0] P12[1] P12[2] P12[0] P12[1] P12[2] w1 w2 w3 P12[0]+1 P12[1] P12[2] P12[0]+1 P12[1]+1 P12[2]+1 P12[0] P12[1] P12[2]+1 cross product: v ^ w = (v2*w3 - w2*v3, v3*w1 - v1*w3, v1*w2 - w1*v2); cross product of second: v ^ w = (b*(c+1) - c*(b+1), c*(a+1) - a*(c+1) , a*(b+1) - b*(a+1)) = ( b - c , c - a , a - b ) cross product of third: v ^ w = (b*(c+1) - b*c, c*a - a*(c+1), a*b - b*a) (b ,-a , 0); (v3_P12.y ,-v3_P12.x , 0); Reasons why I use the third: -Using the first one modifies the x coord, so it generates a plane the ortogonal of which will be a few degrees different when z != 0 and when z =0, thus responsible for soft shiftings at joints where z values change -Adding 1 to the z value will produce the same plane whatever the z value, thus avoiding soft shiftings at joints where z values are different -Then, the third allows for very fine control of the direction that the ortogonal vector takes: simply manipulating the x coord of v3_PR, voilà. */ // BELOW if-else statements needed to correct the orientation of vectors, so there's no discontinuity if (v3_P12.y < 0) { v3_PR = new Vector3(v3_P12.y, -v3_P12.x, 0); v3_PR = v3_PR.normalize(v3_PR); v3_PR = v3_PR.scale(p_width_i[i], v3_PR); //vectors are perfectly normalized and scaled //The problem then must be that they are not properly ortogonal and so appear to have a smaller width. // -not only not ortogonal but actually messed up in some way, i.e. bad coords. circle[half_parallels] = v3_PR; for (int q=half_parallels+1; q<parallels+1; q++) { sinn = Math.sin(angle*(q-half_parallels)); coss = Math.cos(angle*(q-half_parallels)); circle[q] = rotate_v_around_axis(v3_PR, v3_P12, sinn, coss); } circle[0] = circle[parallels]; for (int qq=1; qq<half_parallels; qq++) { sinn = Math.sin(angle*(qq+half_parallels)); coss = Math.cos(angle*(qq+half_parallels)); circle[qq] = rotate_v_around_axis(v3_PR, v3_P12, sinn, coss); } } else { v3_PR = new Vector3(-v3_P12.y, v3_P12.x, 0); //thining problems disappear when both types of y coord are equal, but then shifting appears /* Observations: -if y coord shifted, then no thinnings but yes shiftings -if x coord shifted, THEN PERFECT -if both shifted, then both thinnings and shiftings -if none shifted, then no shiftings but yes thinnings */ v3_PR = v3_PR.normalize(v3_PR); if (null == v3_PR) { Utils.log2("vp_3r is null: most likely a point was repeated in the list, and thus the vector has length zero."); } v3_PR = v3_PR.scale( p_width_i[i], v3_PR); circle[0] = v3_PR; for (int q=1; q<parallels; q++) { sinn = Math.sin(angle*q); coss = Math.cos(angle*q); circle[q] = rotate_v_around_axis(v3_PR, v3_P12, sinn, coss); } circle[parallels] = v3_PR; } // Adding points to main array for (int j=0; j<parallels+1; j++) { all_points[i+extra][j][0] = /*p_i[0][i]*/ px[i] + circle[j].x; all_points[i+extra][j][1] = /*p_i[1][i]*/ py[i] + circle[j].y; all_points[i+extra][j][2] = /*z_values[i]*/ pz[i] + circle[j].z; } } for (int k=0; k<parallels+1; k++) { all_points[n-1+extra][k][0] = /*p_i[0][n-1]*/ px[n-1] + circle[k].x; all_points[n-1+extra][k][1] = /*p_i[1][n-1]*/ py[n-1] + circle[k].y; all_points[n-1+extra][k][2] = /*z_values[n-1]*/ pz[n-1] + circle[k].z; } return all_points; } /** From my former program, A_3D_Editing.java and Pipe.java */ static private Vector3 rotate_v_around_axis(final Vector3 v, final Vector3 axis, final double sin, final double cos) { final Vector3 result = new Vector3(); final Vector3 r = axis.normalize(axis); result.set((cos + (1-cos) * r.x * r.x) * v.x + ((1-cos) * r.x * r.y - r.z * sin) * v.y + ((1-cos) * r.x * r.z + r.y * sin) * v.z, ((1-cos) * r.x * r.y + r.z * sin) * v.x + (cos + (1-cos) * r.y * r.y) * v.y + ((1-cos) * r.y * r.z - r.x * sin) * v.z, ((1-cos) * r.y * r.z - r.y * sin) * v.x + ((1-cos) * r.y * r.z + r.x * sin) * v.y + (cos + (1-cos) * r.z * r.z) * v.z); /* result.x += (cos + (1-cos) * r.x * r.x) * v.x; result.x += ((1-cos) * r.x * r.y - r.z * sin) * v.y; result.x += ((1-cos) * r.x * r.z + r.y * sin) * v.z; result.y += ((1-cos) * r.x * r.y + r.z * sin) * v.x; result.y += (cos + (1-cos) * r.y * r.y) * v.y; result.y += ((1-cos) * r.y * r.z - r.x * sin) * v.z; result.z += ((1-cos) * r.y * r.z - r.y * sin) * v.x; result.z += ((1-cos) * r.y * r.z + r.x * sin) * v.y; result.z += (cos + (1-cos) * r.z * r.z) * v.z; */ return result; } synchronized private Object[] getTransformedData() { final int n_points = this.n_points; final double[][] p = transformPoints(this.p, n_points); final double[][] p_l = transformPoints(this.p_l, n_points); final double[][] p_r = transformPoints(this.p_r, n_points); final double[][] p_i = transformPoints(this.p_i, this.p_i[0].length); // whatever length it has final double[] p_width = new double[n_points]; // first contains the data, then the transformed data System.arraycopy(this.p_width, 0, p_width, 0, n_points); final double[] p_width_i = new double[this.p_width_i.length]; // first contains the data, then the transformed data System.arraycopy(this.p_width_i, 0, p_width_i, 0, p_width_i.length); // p_width: same rule as for Ball: average of x and y double[][] pw = new double[2][n_points]; for (int i=0; i<n_points; i++) { pw[0][i] = this.p[0][i] + p_width[i]; //built relative to the untransformed points! pw[1][i] = this.p[1][i] + p_width[i]; } pw = transformPoints(pw); //final double[] p_width = new double[n_points]; for (int i=0; i<n_points; i++) { // plain average of differences in X and Y axis, relative to the transformed points. p_width[i] = (Math.abs(pw[0][i] - p[0][i]) + Math.abs(pw[1][i] - p[1][i])) / 2; } // same with p_width_i double[][] pwi = new double[2][p_i[0].length]; for (int i=0; i<p_i[0].length; i++) { pwi[0][i] = this.p_i[0][i] + p_width_i[i]; //built relative to the untransformed points! pwi[1][i] = this.p_i[1][i] + p_width_i[i]; } pwi = transformPoints(pwi); //final double[] p_width_i = new double[p_i[0].length]; for (int i=0; i<p_i[0].length; i++) { // plain average of differences in X and Y axis, relative to the transformed points. p_width_i[i] = (Math.abs(pwi[0][i] - p_i[0][i]) + Math.abs(pwi[1][i] - p_i[1][i])) / 2; } return new Object[]{p, p_l, p_r, p_i, p_width, p_width_i}; } /** Returns a non-calibrated VectorString3D. */ synchronized public VectorString3D asVectorString3D() { // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } final int n = p_i[0].length; final int mm = n_points; final double[] z_values = new double[n]; final int interval_points = n / (mm-1); double z_val = 0; double z_val_next = 0; double z_diff = 0; int c = 0; double delta = 0; for (int j=0; j<mm-1; j++) { z_val = layer_set.getLayer(p_layer[j]).getZ(); z_val_next = layer_set.getLayer(p_layer[j+1]).getZ(); z_diff = z_val_next - z_val; delta = z_diff/interval_points; z_values[c] = (0 == j ? z_val : z_values[c-1]) + delta; for (int k=1; k<interval_points; k++) { c++; z_values[c] = z_values[c-1] + delta; } c++; } //setting last point z_values[n-1] = layer_set.getLayer(p_layer[mm-1]).getZ(); final double[] px = p_i[0]; final double[] py = p_i[1]; final double[] pz = z_values; VectorString3D vs = null; try { vs = new VectorString3D(px, py, pz, false); vs.addDependent(p_width_i); } catch (Exception e) { IJError.print(e); } return vs; } public String getInfo() { if (-1 == n_points) setupForDisplay(); //reload // measure length double len = 0; if (n_points > 1) { VectorString3D vs = asVectorString3D(); vs.calibrate(this.layer_set.getCalibration()); len = vs.computeLength(); // no resampling } return new StringBuffer("Length: ").append(Utils.cutNumber(len, 2, true)).append(' ').append(this.layer_set.getCalibration().getUnits()).append('\n').toString(); } /** @param area is expected in world coordinates. */ public boolean intersects(final Area area, final double z_first, final double z_last) { // find lowest and highest Z double min_z = Double.MAX_VALUE; double max_z = 0; for (int i=0; i<n_points; i++) { double laz =layer_set.getLayer(p_layer[i]).getZ(); if (laz < min_z) min_z = laz; if (laz > max_z) max_z = laz; } if (z_last < min_z || z_first > max_z) return false; // check the roi for (int i=0; i<n_points; i++) { final Polygon[] pol = getSubPerimeters(layer_set.getLayer(p_layer[i])); if (null == pol) continue; for (int k=0; k<pol.length; k++) { Area a = new Area(pol[k]); // perimeters already in world coords a.intersect(area); Rectangle r = a.getBounds(); if (0 != r.width && 0 != r.height) return true; } } return false; } /** Expects Rectangle in world coords. */ public boolean intersects(final Layer layer, final Rectangle r) { final Polygon[] pol = getSubPerimeters(layer); // transformed if (null == pol) return false; for (Polygon p : pol) if (new Area(p).intersects(r.x, r.y, r.width, r.height)) return true; return false; } /** Expects Area in world coords. */ public boolean intersects(final Layer layer, final Area area) { final Polygon[] pol = getSubPerimeters(layer); // transformed if (null == pol) return false; for (Polygon p : pol) if (M.intersects(new Area(p), area)) return true; return false; } /** Returns the bounds of this object as it shows in the given layer, set into @param r. */ public Rectangle getBounds(final Rectangle r, final Layer layer) { // obtain the already transformed subperimeters final Polygon[] pol = getSubPerimeters(layer); if (null == pol) { if (null == r) return new Rectangle(); r.x = 0; r.y = 0; r.width = 0; r.height = 0; return r; } final Area area = new Area(); for (Polygon p : pol) { area.add(new Area(p)); } final Rectangle b = area.getBounds(); if (null == r) return b; r.setBounds(b.x, b.y, b.width, b.height); return r; } // debug --------------- static private void showShape(final Shape shape) { Area area = new Area(shape); Rectangle b = area.getBounds(); AffineTransform trans = new AffineTransform(); trans.translate(-b.x, -b.y); area = area.createTransformedArea(trans); ij.process.ByteProcessor bp = new ij.process.ByteProcessor(b.width, b.height); ij.gui.ShapeRoi sr = new ij.gui.ShapeRoi(area); ij.ImagePlus imp = new ij.ImagePlus("pipe area", bp); imp.setRoi(sr); bp.setValue(255); sr.drawPixels(bp); imp.show(); } public ResultsTable measure(ResultsTable rt) { if (-1 == n_points) setupForDisplay(); //reload if (0 == n_points) return rt; if (null == rt) rt = Utils.createResultsTable("Pipe results", new String[]{"id", "length", "name-id"}); // measure length double len = 0; Calibration cal = layer_set.getCalibration(); if (n_points > 1) { VectorString3D vs = asVectorString3D(); vs.calibrate(cal); len = vs.computeLength(); // no resampling } rt.incrementCounter(); rt.addLabel("units", cal.getUnit()); rt.addValue(0, this.id); rt.addValue(1, len); rt.addValue(2, getNameId()); return rt; } @Override final Class getInternalDataPackageClass() { return DPPipe.class; } @Override synchronized Object getDataPackage() { return new DPPipe(this); } static private final class DPPipe extends Displayable.DataPackage { final double[][] p, p_l, p_r, p_i; final double[] p_width, p_width_i; final long[] p_layer; DPPipe(final Pipe pipe) { super(pipe); // store copies of all arrays this.p = new double[][]{Utils.copy(pipe.p[0], pipe.n_points), Utils.copy(pipe.p[1], pipe.n_points)}; this.p_r = new double[][]{Utils.copy(pipe.p_r[0], pipe.n_points), Utils.copy(pipe.p_r[1], pipe.n_points)}; this.p_l = new double[][]{Utils.copy(pipe.p_l[0], pipe.n_points), Utils.copy(pipe.p_l[1], pipe.n_points)}; this.p_width = Utils.copy(pipe.p_width, pipe.n_points); this.p_i = new double[][]{Utils.copy(pipe.p_i[0], pipe.p_i[0].length), Utils.copy(pipe.p_i[1], pipe.p_i[0].length)}; this.p_width_i = Utils.copy(pipe.p_width_i, pipe.p_width_i.length); this.p_layer = new long[pipe.n_points]; System.arraycopy(pipe.p_layer, 0, this.p_layer, 0, pipe.n_points); } @Override final boolean to2(final Displayable d) { super.to1(d); final Pipe pipe = (Pipe)d; final int len = p[0].length; // == n_points, since it was cropped on copy pipe.p = new double[][]{Utils.copy(p[0], len), Utils.copy(p[1], len)}; pipe.n_points = p[0].length; pipe.p_r = new double[][]{Utils.copy(p_r[0], len), Utils.copy(p_r[1], len)}; pipe.p_l = new double[][]{Utils.copy(p_l[0], len), Utils.copy(p_l[1], len)}; pipe.p_layer = new long[len]; System.arraycopy(p_layer, 0, pipe.p_layer, 0, len); pipe.p_width = Utils.copy(p_width, len); pipe.p_i = new double[][]{Utils.copy(p_i[0], p_i[0].length), Utils.copy(p_i[1], p_i[1].length)}; pipe.p_width_i = Utils.copy(p_width_i, p_width_i.length); return true; } } /** Reverses the order of the points in the arrays. */ synchronized public void reverse() { for (int i=0; i<n_points/2; i++) { final int j = n_points -1 -i; _swap(p, i, j); _swap(p_l, i, j); _swap(p_r, i, j); long l = p_layer[i]; // we love java and it's lack of primitive abstraction. p_layer[i] = p_layer[j]; p_layer[j] = l; double r = p_width[i]; p_width[i] = p_width[j]; p_width[j] = r; } // what was left is now right: double[][] a = p_l; p_l = p_r; p_r = a; // Nothing should change, but let's see it: generateInterpolatedPoints(0.05); } /** Helper function to swap both X and Y from index i to j. */ static private final void _swap(final double[][] a, final int i, final int j) { for (int k=0; k<2; k++) { double tmp = a[k][i]; a[k][i] = a[k][j]; a[k][j] = tmp; } } }
true
true
public void paint(final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer) { if (0 == n_points) return; if (-1 == n_points) { // load points from the database setupForDisplay(); } //arrange transparency Composite original_composite = null; if (alpha != 1.0f) { original_composite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } final boolean no_color_cues = "true".equals(project.getProperty("no_color_cues")); final long layer_id = active_layer.getId(); if (active) { // draw/fill points final int oval_radius = (int)Math.ceil(4 / magnification); final int oval_corr = (int)Math.ceil(3 / magnification); for (int j=0; j<n_points; j++) { //TODO there is room for optimization, operations are being done twice or 3 times; BUT is the creation of new variables as costly as the calculations? I have no idea. if (layer_id != p_layer[j]) continue; //draw big ovals at backbone points DisplayCanvas.drawHandle(g, (int)p[0][j], (int)p[1][j], magnification); g.setColor(color); //fill small ovals at control points g.fillOval((int)p_l[0][j] -oval_corr, (int)p_l[1][j] -oval_corr, oval_radius, oval_radius); g.fillOval((int)p_r[0][j] -oval_corr, (int)p_r[1][j] -oval_corr, oval_radius, oval_radius); //draw lines between backbone and control points g.drawLine((int)p[0][j], (int)p[1][j], (int)p_l[0][j], (int)p_l[1][j]); g.drawLine((int)p[0][j], (int)p[1][j], (int)p_r[0][j], (int)p_r[1][j]); // label the first point distinctively: if (0 == j) { Composite comp = g.getComposite(); g.setXORMode(Color.white); g.drawString("1", (int)(p[0][0] + (4.0 / magnification)), (int)p[1][0]); // displaced 4 screen pixels to the right g.setComposite(comp); } } } // paint the tube in 2D: if (n_points > 1 && p_i[0].length > 1) { // need the second check for repaints that happen before generating the interpolated points. double angle = 0; double a0 = Math.toRadians(0); double a90 = Math.toRadians(90); double a180 = Math.toRadians(180); double a270 = Math.toRadians(270); final int n = p_i[0].length; final double[] r_side_x = new double[n]; final double[] r_side_y = new double[n]; final double[] l_side_x = new double[n]; final double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; final double z_current = active_layer.getZ(); if (no_color_cues) { // paint a tiny bit where it should! g.setColor(this.color); } for (int j=0; j<n_points; j++) { // at least looping through 2 points, as guaranteed by the preconditions checking if (no_color_cues) { if (layer_id == p_layer[j]) { // paint normally } else { // else if crossed the current layer, paint segment as well if (0 == j) continue; double z1 = layer_set.getLayer(p_layer[j-1]).getZ(); double z2 = layer_set.getLayer(p_layer[j]).getZ(); if ( (z1 < z_current && z_current < z2) || (z2 < z_current && z_current < z1) ) { // paint normally, in this pipe's color } else { continue; } } } else { double z = layer_set.getLayer(p_layer[j]).getZ(); if (z < z_current) g.setColor(Color.red); else if (z == z_current) g.setColor(this.color); else g.setColor(Color.blue); } int fi = 0; int la = j * 20 -1; if (0 != j) fi = (j * 20) - 10; // 10 is half a segment if (n_points -1 != j) la += 10; // same //= j * 20 + 9; if (la >= r_side_x.length) la = r_side_x.length-2; // quick fix. -2 so that the k+1 below can work if (fi > la) fi = la; try { for (int k=fi; k<=la; k++) { g.drawLine((int)r_side_x[k], (int)r_side_y[k], (int)r_side_x[k+1], (int)r_side_y[k+1]); g.drawLine((int)l_side_x[k], (int)l_side_y[k], (int)l_side_x[k+1], (int)l_side_y[k+1]); } } catch (Exception ee) { Utils.log2("Pipe paint failed with: fi=" + fi + " la=" + la + " n_points=" + n_points + " r_side_x.length=" + r_side_x.length); // WARNING still something is wrong with the synchronization over the arrays ... despite this error being patched with the line above: // if (la >= r_side_x.length) r_side_x.length-2; // quick fix // // ADDING the synchronized keyword to many methods involving n_points did not fix it; neither to crop arrays and get the new n_points from the getTransformedData() returned p array. } } } //Transparency: fix alpha composite back to original. if (null != original_composite) { g.setComposite(original_composite); } }
public void paint(final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer) { if (0 == n_points) return; if (-1 == n_points) { // load points from the database setupForDisplay(); } //arrange transparency Composite original_composite = null; if (alpha != 1.0f) { original_composite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; double[][] p_r = this.p_r; double[][] p_l = this.p_l; double[][] p_i = this.p_i; double[] p_width = this.p_width; double[] p_width_i = this.p_width_i; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; p_l = (double[][])ob[1]; p_r = (double[][])ob[2]; p_i = (double[][])ob[3]; p_width = (double[])ob[4]; p_width_i = (double[])ob[5]; } final boolean no_color_cues = "true".equals(project.getProperty("no_color_cues")); final long layer_id = active_layer.getId(); if (active) { // draw/fill points final int oval_radius = (int)Math.ceil(4 / magnification); final int oval_corr = (int)Math.ceil(3 / magnification); for (int j=0; j<n_points; j++) { //TODO there is room for optimization, operations are being done twice or 3 times; BUT is the creation of new variables as costly as the calculations? I have no idea. if (layer_id != p_layer[j]) continue; //draw big ovals at backbone points DisplayCanvas.drawHandle(g, (int)p[0][j], (int)p[1][j], magnification); g.setColor(color); //fill small ovals at control points g.fillOval((int)p_l[0][j] -oval_corr, (int)p_l[1][j] -oval_corr, oval_radius, oval_radius); g.fillOval((int)p_r[0][j] -oval_corr, (int)p_r[1][j] -oval_corr, oval_radius, oval_radius); //draw lines between backbone and control points g.drawLine((int)p[0][j], (int)p[1][j], (int)p_l[0][j], (int)p_l[1][j]); g.drawLine((int)p[0][j], (int)p[1][j], (int)p_r[0][j], (int)p_r[1][j]); // label the first point distinctively: if (0 == j) { Composite comp = g.getComposite(); g.setColor(Color.white); g.setXORMode(Color.green); g.drawString("1", (int)(p[0][0] + (4.0 / magnification)), (int)p[1][0]); // displaced 4 screen pixels to the right g.setComposite(comp); } } } // paint the tube in 2D: if (n_points > 1 && p_i[0].length > 1) { // need the second check for repaints that happen before generating the interpolated points. double angle = 0; double a0 = Math.toRadians(0); double a90 = Math.toRadians(90); double a180 = Math.toRadians(180); double a270 = Math.toRadians(270); final int n = p_i[0].length; final double[] r_side_x = new double[n]; final double[] r_side_y = new double[n]; final double[] l_side_x = new double[n]; final double[] l_side_y = new double[n]; int m = n-1; for (int i=0; i<n-1; i++) { angle = Math.atan2(p_i[0][i+1] - p_i[0][i], p_i[1][i+1] - p_i[1][i]); r_side_x[i] = p_i[0][i] + Math.sin(angle+a90) * p_width_i[i]; //sin and cos are inverted, but works better like this. WHY ?? r_side_y[i] = p_i[1][i] + Math.cos(angle+a90) * p_width_i[i]; l_side_x[i] = p_i[0][i] + Math.sin(angle-a90) * p_width_i[i]; l_side_y[i] = p_i[1][i] + Math.cos(angle-a90) * p_width_i[i]; } angle = Math.atan2(p_i[0][m] - p_i[0][m-1], p_i[1][m] - p_i[1][m-1]); r_side_x[m] = p_i[0][m] + Math.sin(angle+a90) * p_width_i[m]; r_side_y[m] = p_i[1][m] + Math.cos(angle+a90) * p_width_i[m]; l_side_x[m] = p_i[0][m] + Math.sin(angle-a90) * p_width_i[m]; l_side_y[m] = p_i[1][m] + Math.cos(angle-a90) * p_width_i[m]; final double z_current = active_layer.getZ(); if (no_color_cues) { // paint a tiny bit where it should! g.setColor(this.color); } for (int j=0; j<n_points; j++) { // at least looping through 2 points, as guaranteed by the preconditions checking if (no_color_cues) { if (layer_id == p_layer[j]) { // paint normally } else { // else if crossed the current layer, paint segment as well if (0 == j) continue; double z1 = layer_set.getLayer(p_layer[j-1]).getZ(); double z2 = layer_set.getLayer(p_layer[j]).getZ(); if ( (z1 < z_current && z_current < z2) || (z2 < z_current && z_current < z1) ) { // paint normally, in this pipe's color } else { continue; } } } else { double z = layer_set.getLayer(p_layer[j]).getZ(); if (z < z_current) g.setColor(Color.red); else if (z == z_current) g.setColor(this.color); else g.setColor(Color.blue); } int fi = 0; int la = j * 20 -1; if (0 != j) fi = (j * 20) - 10; // 10 is half a segment if (n_points -1 != j) la += 10; // same //= j * 20 + 9; if (la >= r_side_x.length) la = r_side_x.length-2; // quick fix. -2 so that the k+1 below can work if (fi > la) fi = la; try { for (int k=fi; k<=la; k++) { g.drawLine((int)r_side_x[k], (int)r_side_y[k], (int)r_side_x[k+1], (int)r_side_y[k+1]); g.drawLine((int)l_side_x[k], (int)l_side_y[k], (int)l_side_x[k+1], (int)l_side_y[k+1]); } } catch (Exception ee) { Utils.log2("Pipe paint failed with: fi=" + fi + " la=" + la + " n_points=" + n_points + " r_side_x.length=" + r_side_x.length); // WARNING still something is wrong with the synchronization over the arrays ... despite this error being patched with the line above: // if (la >= r_side_x.length) r_side_x.length-2; // quick fix // // ADDING the synchronized keyword to many methods involving n_points did not fix it; neither to crop arrays and get the new n_points from the getTransformedData() returned p array. } } } //Transparency: fix alpha composite back to original. if (null != original_composite) { g.setComposite(original_composite); } }
diff --git a/src/org/utils/shape/ShapeCube.java b/src/org/utils/shape/ShapeCube.java index 6dcca67..db9509f 100644 --- a/src/org/utils/shape/ShapeCube.java +++ b/src/org/utils/shape/ShapeCube.java @@ -1,63 +1,63 @@ package org.utils.shape; import java.awt.Graphics; import org.utils.transform.Projection; /** * Geometry for cube. * @author kerry * */ public class ShapeCube extends Geometry { @Override public void globe(int M, int N) { // vertices should contain the normal for each vertice. - vertices = new double[][] { { 1, 1, 1, 1, 1, 1 }, - { 1, -1, 1, 1, -1, 1 }, { -1, -1, 1, -1, -1, 1 }, - { -1, 1, 1, -1, 1, 1 }, { 1, 1, -1, 1, 1, -1 }, - { 1, -1, -1, 1, -1, -1 }, { -1, -1, -1, -1, -1, -1 }, - { -1, 1, -1, -1, 1, -1 }, { 1, 1, 1, 1, 1, 1 }, - { 1, -1, 1, 1, -1, 1 }, { 1, -1, -1, 1, -1, -1 }, - { 1, 1, -1, 1, 1, -1 }, { -1, 1, 1, -1, 1, 1 }, - { -1, -1, 1, -1, -1, 1 }, { -1, -1, -1, -1, -1, -1 }, - { -1, 1, -1, -1, 1, -1 }, { 1, 1, 1, 1, 1, 1 }, - { -1, 1, 1, -1, 1, 1 }, { -1, 1, -1, -1, 1, -1 }, - { 1, 1, -1, 1, 1, -1 }, { 1, -1, 1, 1, -1, 1 }, - { -1, -1, 1, -1, -1, 1 }, { -1, -1, -1, -1, -1, -1 }, - { 1, -1, -1, 1, -1, -1 }, }; + vertices = new double[][] { { 1, 1, 1, 0, 0, 1 }, + { 1, -1, 1, 0, 0, 1 }, { -1, -1, 1, 0, 0, 1 }, + { -1, 1, 1, 0, 0, 1 }, { 1, 1, -1, 0, 0, -1 }, + { 1, -1, -1, 0, 0, -1 }, { -1, -1, -1, 0, 0, -1 }, + { -1, 1, -1, 0, 0, -1 }, { 1, 1, 1, 1, 0, 0 }, + { 1, -1, 1, 1, 0, 0 }, { 1, -1, -1, 1, 0, 0 }, + { 1, 1, -1, 1, 0, 0 }, { -1, 1, 1, -1, 0, 0 }, + { -1, -1, 1, -1, 0, 0 }, { -1, -1, -1, -1, 0, 0 }, + { -1, 1, -1, -1, 0, 0 }, { 1, 1, 1, 0, 1, 0 }, + { -1, 1, 1, 0, 1, 0 }, { -1, 1, -1, 0, 1, 0 }, + { 1, 1, -1, 0, 1, 0 }, { 1, -1, 1, 0, -1, 0 }, + { -1, -1, 1, 0, -1, 0 }, { -1, -1, -1, 0, -1, 0 }, + { 1, -1, -1, 0, -1, 0 }, }; faces = new int[6][4]; for (int i = 0; i < faces.length; i++) { faces[i] = new int[] { i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3 }; } this.m.identity(); } @Override double plotX(double u, double v) { return 0; } @Override double plotY(double u, double v) { return 0; } @Override double plotZ(double u, double v) { return 0; } @Override public void drawShape(Graphics g, Projection p) { for (int i = 0; i < faces.length; i++) { drawEdge(vertices[faces[i][0]], vertices[faces[i][1]], g, p); drawEdge(vertices[faces[i][1]], vertices[faces[i][2]], g, p); drawEdge(vertices[faces[i][2]], vertices[faces[i][3]], g, p); drawEdge(vertices[faces[i][3]], vertices[faces[i][0]], g, p); } } }
true
true
public void globe(int M, int N) { // vertices should contain the normal for each vertice. vertices = new double[][] { { 1, 1, 1, 1, 1, 1 }, { 1, -1, 1, 1, -1, 1 }, { -1, -1, 1, -1, -1, 1 }, { -1, 1, 1, -1, 1, 1 }, { 1, 1, -1, 1, 1, -1 }, { 1, -1, -1, 1, -1, -1 }, { -1, -1, -1, -1, -1, -1 }, { -1, 1, -1, -1, 1, -1 }, { 1, 1, 1, 1, 1, 1 }, { 1, -1, 1, 1, -1, 1 }, { 1, -1, -1, 1, -1, -1 }, { 1, 1, -1, 1, 1, -1 }, { -1, 1, 1, -1, 1, 1 }, { -1, -1, 1, -1, -1, 1 }, { -1, -1, -1, -1, -1, -1 }, { -1, 1, -1, -1, 1, -1 }, { 1, 1, 1, 1, 1, 1 }, { -1, 1, 1, -1, 1, 1 }, { -1, 1, -1, -1, 1, -1 }, { 1, 1, -1, 1, 1, -1 }, { 1, -1, 1, 1, -1, 1 }, { -1, -1, 1, -1, -1, 1 }, { -1, -1, -1, -1, -1, -1 }, { 1, -1, -1, 1, -1, -1 }, }; faces = new int[6][4]; for (int i = 0; i < faces.length; i++) { faces[i] = new int[] { i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3 }; } this.m.identity(); }
public void globe(int M, int N) { // vertices should contain the normal for each vertice. vertices = new double[][] { { 1, 1, 1, 0, 0, 1 }, { 1, -1, 1, 0, 0, 1 }, { -1, -1, 1, 0, 0, 1 }, { -1, 1, 1, 0, 0, 1 }, { 1, 1, -1, 0, 0, -1 }, { 1, -1, -1, 0, 0, -1 }, { -1, -1, -1, 0, 0, -1 }, { -1, 1, -1, 0, 0, -1 }, { 1, 1, 1, 1, 0, 0 }, { 1, -1, 1, 1, 0, 0 }, { 1, -1, -1, 1, 0, 0 }, { 1, 1, -1, 1, 0, 0 }, { -1, 1, 1, -1, 0, 0 }, { -1, -1, 1, -1, 0, 0 }, { -1, -1, -1, -1, 0, 0 }, { -1, 1, -1, -1, 0, 0 }, { 1, 1, 1, 0, 1, 0 }, { -1, 1, 1, 0, 1, 0 }, { -1, 1, -1, 0, 1, 0 }, { 1, 1, -1, 0, 1, 0 }, { 1, -1, 1, 0, -1, 0 }, { -1, -1, 1, 0, -1, 0 }, { -1, -1, -1, 0, -1, 0 }, { 1, -1, -1, 0, -1, 0 }, }; faces = new int[6][4]; for (int i = 0; i < faces.length; i++) { faces[i] = new int[] { i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3 }; } this.m.identity(); }
diff --git a/src/main/java/com/celements/calendar/navigation/factories/NavigationDetailsFactory.java b/src/main/java/com/celements/calendar/navigation/factories/NavigationDetailsFactory.java index bf4013a..4ddff3f 100644 --- a/src/main/java/com/celements/calendar/navigation/factories/NavigationDetailsFactory.java +++ b/src/main/java/com/celements/calendar/navigation/factories/NavigationDetailsFactory.java @@ -1,86 +1,86 @@ package com.celements.calendar.navigation.factories; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xwiki.model.reference.DocumentReference; import com.celements.calendar.Calendar; import com.celements.calendar.ICalendar; import com.celements.calendar.IEvent; import com.celements.calendar.manager.IEventManager; import com.celements.calendar.search.EventSearchQuery; import com.xpn.xwiki.web.Utils; public class NavigationDetailsFactory implements INavigationDetailsFactory { private static final Log LOGGER = LogFactory.getFactory().getInstance( NavigationDetailsFactory.class); private IEventManager eventMgr; public NavigationDetails getNavigationDetails(Date startDate, int offset) { return new NavigationDetails(startDate, offset); } public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef, IEvent event) { return getNavigationDetails(calConfigDocRef, event, null); } public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef, IEvent event, EventSearchQuery query) { LOGGER.debug("getNavigationDetails for '" + event + "'"); Date eventDate = event.getEventDate(); if (eventDate != null) { ICalendar cal = new Calendar(calConfigDocRef, false); cal.setStartDate(eventDate); int offset = 0; int nb = 10; int eventIndex, start = 0; List<IEvent> events; boolean hasMore, notFound; do { if (query == null) { events = getEventMgr().getEventsInternal(cal, start, nb); } else { events = getEventMgr().searchEvents(cal, query).getEventList(start, nb); } hasMore = events.size() == nb; eventIndex = events.indexOf(event); notFound = eventIndex < 0; offset = start + eventIndex; start = start + nb; nb = nb * 2; if (LOGGER.isDebugEnabled()) { LOGGER.debug("getNavigationDetails: events '" + events + "'"); LOGGER.debug("getNavigationDetails: index for event '" + eventIndex); } } while (notFound && hasMore); if (!notFound) { NavigationDetails navDetail = new NavigationDetails(cal.getStartDate(), offset); LOGGER.debug("getNavigationDetails: found '" + navDetail + "'"); return navDetail; } else { - LOGGER.debug("getNavigationDetails: not found"); + LOGGER.warn("getNavigationDetails: not found"); } } else { LOGGER.error("getNavigationDetails: eventDate is null for '" + event + "'"); } return null; } private IEventManager getEventMgr() { if (eventMgr == null) { eventMgr = Utils.getComponent(IEventManager.class); } return eventMgr; } void injectEventMgr(IEventManager eventMgr) { this.eventMgr = eventMgr; } }
true
true
public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef, IEvent event, EventSearchQuery query) { LOGGER.debug("getNavigationDetails for '" + event + "'"); Date eventDate = event.getEventDate(); if (eventDate != null) { ICalendar cal = new Calendar(calConfigDocRef, false); cal.setStartDate(eventDate); int offset = 0; int nb = 10; int eventIndex, start = 0; List<IEvent> events; boolean hasMore, notFound; do { if (query == null) { events = getEventMgr().getEventsInternal(cal, start, nb); } else { events = getEventMgr().searchEvents(cal, query).getEventList(start, nb); } hasMore = events.size() == nb; eventIndex = events.indexOf(event); notFound = eventIndex < 0; offset = start + eventIndex; start = start + nb; nb = nb * 2; if (LOGGER.isDebugEnabled()) { LOGGER.debug("getNavigationDetails: events '" + events + "'"); LOGGER.debug("getNavigationDetails: index for event '" + eventIndex); } } while (notFound && hasMore); if (!notFound) { NavigationDetails navDetail = new NavigationDetails(cal.getStartDate(), offset); LOGGER.debug("getNavigationDetails: found '" + navDetail + "'"); return navDetail; } else { LOGGER.debug("getNavigationDetails: not found"); } } else { LOGGER.error("getNavigationDetails: eventDate is null for '" + event + "'"); } return null; }
public NavigationDetails getNavigationDetails(DocumentReference calConfigDocRef, IEvent event, EventSearchQuery query) { LOGGER.debug("getNavigationDetails for '" + event + "'"); Date eventDate = event.getEventDate(); if (eventDate != null) { ICalendar cal = new Calendar(calConfigDocRef, false); cal.setStartDate(eventDate); int offset = 0; int nb = 10; int eventIndex, start = 0; List<IEvent> events; boolean hasMore, notFound; do { if (query == null) { events = getEventMgr().getEventsInternal(cal, start, nb); } else { events = getEventMgr().searchEvents(cal, query).getEventList(start, nb); } hasMore = events.size() == nb; eventIndex = events.indexOf(event); notFound = eventIndex < 0; offset = start + eventIndex; start = start + nb; nb = nb * 2; if (LOGGER.isDebugEnabled()) { LOGGER.debug("getNavigationDetails: events '" + events + "'"); LOGGER.debug("getNavigationDetails: index for event '" + eventIndex); } } while (notFound && hasMore); if (!notFound) { NavigationDetails navDetail = new NavigationDetails(cal.getStartDate(), offset); LOGGER.debug("getNavigationDetails: found '" + navDetail + "'"); return navDetail; } else { LOGGER.warn("getNavigationDetails: not found"); } } else { LOGGER.error("getNavigationDetails: eventDate is null for '" + event + "'"); } return null; }
diff --git a/server/plugins/eu.esdihumboldt.hale.server.templates/src/eu/esdihumboldt/hale/server/templates/impl/TemplateScavengerImpl.java b/server/plugins/eu.esdihumboldt.hale.server.templates/src/eu/esdihumboldt/hale/server/templates/impl/TemplateScavengerImpl.java index 4653d79e7..7831c8e7a 100644 --- a/server/plugins/eu.esdihumboldt.hale.server.templates/src/eu/esdihumboldt/hale/server/templates/impl/TemplateScavengerImpl.java +++ b/server/plugins/eu.esdihumboldt.hale.server.templates/src/eu/esdihumboldt/hale/server/templates/impl/TemplateScavengerImpl.java @@ -1,151 +1,152 @@ /* * Copyright (c) 2013 Data Harmonisation Panel * * All rights reserved. This program and the accompanying materials are made * available under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Data Harmonisation Panel <http://www.dhpanel.eu> */ package eu.esdihumboldt.hale.server.templates.impl; import java.io.File; import java.io.IOException; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import de.cs3d.util.logging.ALogger; import de.cs3d.util.logging.ALoggerFactory; import eu.esdihumboldt.hale.common.core.io.project.ProjectInfo; import eu.esdihumboldt.hale.common.headless.scavenger.ProjectReference; import eu.esdihumboldt.hale.server.db.orient.DatabaseHelper; import eu.esdihumboldt.hale.server.model.Template; import eu.esdihumboldt.hale.server.templates.TemplateScavenger; import eu.esdihumboldt.util.blueprints.entities.NonUniqueResultException; import eu.esdihumboldt.util.scavenger.AbstractResourceScavenger; /** * Scavenger for (template) projects. * * @author Simon Templer */ public class TemplateScavengerImpl extends AbstractResourceScavenger<ProjectReference<Void>> implements TemplateScavenger { private static final ALogger log = ALoggerFactory.getLogger(TemplateScavengerImpl.class); private final ThreadLocal<OrientGraph> graph = new ThreadLocal<>(); /** * Create a template project scavenger. * * @param scavengeLocation the location to scan, if the location does not * exist or is not accessible, a default location inside the * platform instance location is used */ public TemplateScavengerImpl(File scavengeLocation) { super(scavengeLocation, "templates"); triggerScan(); } @Override protected void onRemove(ProjectReference<Void> reference, String resourceId) { // invalidate database reference (if it exists) try { Template template = Template.getByTemplateId(graph.get(), resourceId); if (template != null) { template.setValid(false); log.info("Template {} was removed - updating status to invalid", resourceId); } } catch (NonUniqueResultException e) { log.error("Duplicate template representation in database"); } } @Override protected ProjectReference<Void> loadReference(File resourceFolder, String resourceFileName, String resourceId) throws IOException { ProjectReference<Void> ref = new ProjectReference<>(resourceFolder, resourceFileName, resourceId, null); return ref; } @Override public synchronized void triggerScan() { // provide a graph for use in updateResource and onRemove graph.set(DatabaseHelper.getGraph()); try { super.triggerScan(); /* * Check if there are templates in the database that no longer have * an associated template in the file system. */ for (Template template : Template.findAll(graph.get())) { if (template.isValid() && getReference(template.getTemplateId()) == null) { // invalidate template w/ missing resource template.setValid(false); log.warn("Invalidated template {}, the resource folder is missing", template.getTemplateId()); } } } finally { graph.get().shutdown(); graph.set(null); } } @Override protected void onAdd(ProjectReference<Void> reference, String resourceId) { reference.update(null); Template template; try { // get existing representation in database template = Template.getByTemplateId(graph.get(), resourceId); } catch (NonUniqueResultException e) { log.error("Duplicate template representation in database"); return; } if (template != null) { // update valid status boolean valid = reference.getProjectInfo() != null; template.setValid(valid); log.info("Updating template {} - {}", resourceId, (valid) ? ("valid") : ("invalid")); } else { /* * Only create a new database reference if the project actually is * valid */ if (reference.getProjectInfo() != null) { ProjectInfo info = reference.getProjectInfo(); // create new template representation in DB template = Template.create(graph.get()); // populated with resource ID and values from project template.setTemplateId(resourceId); template.setName(info.getName()); template.setAuthor(info.getAuthor()); template.setDescription(info.getDescription()); + template.setValid(true); log.info("Creating database representation for template {}", resourceId); } } } @Override protected void updateResource(ProjectReference<Void> reference, String resourceId) { // nothing to do } }
true
true
protected void onAdd(ProjectReference<Void> reference, String resourceId) { reference.update(null); Template template; try { // get existing representation in database template = Template.getByTemplateId(graph.get(), resourceId); } catch (NonUniqueResultException e) { log.error("Duplicate template representation in database"); return; } if (template != null) { // update valid status boolean valid = reference.getProjectInfo() != null; template.setValid(valid); log.info("Updating template {} - {}", resourceId, (valid) ? ("valid") : ("invalid")); } else { /* * Only create a new database reference if the project actually is * valid */ if (reference.getProjectInfo() != null) { ProjectInfo info = reference.getProjectInfo(); // create new template representation in DB template = Template.create(graph.get()); // populated with resource ID and values from project template.setTemplateId(resourceId); template.setName(info.getName()); template.setAuthor(info.getAuthor()); template.setDescription(info.getDescription()); log.info("Creating database representation for template {}", resourceId); } } }
protected void onAdd(ProjectReference<Void> reference, String resourceId) { reference.update(null); Template template; try { // get existing representation in database template = Template.getByTemplateId(graph.get(), resourceId); } catch (NonUniqueResultException e) { log.error("Duplicate template representation in database"); return; } if (template != null) { // update valid status boolean valid = reference.getProjectInfo() != null; template.setValid(valid); log.info("Updating template {} - {}", resourceId, (valid) ? ("valid") : ("invalid")); } else { /* * Only create a new database reference if the project actually is * valid */ if (reference.getProjectInfo() != null) { ProjectInfo info = reference.getProjectInfo(); // create new template representation in DB template = Template.create(graph.get()); // populated with resource ID and values from project template.setTemplateId(resourceId); template.setName(info.getName()); template.setAuthor(info.getAuthor()); template.setDescription(info.getDescription()); template.setValid(true); log.info("Creating database representation for template {}", resourceId); } } }
diff --git a/src/de/danoeh/antennapod/syndication/util/SyndTypeUtils.java b/src/de/danoeh/antennapod/syndication/util/SyndTypeUtils.java index 5e9494c9..16ef0243 100644 --- a/src/de/danoeh/antennapod/syndication/util/SyndTypeUtils.java +++ b/src/de/danoeh/antennapod/syndication/util/SyndTypeUtils.java @@ -1,37 +1,37 @@ package de.danoeh.antennapod.syndication.util; import org.apache.commons.io.FilenameUtils; import android.webkit.MimeTypeMap; /** Utility class for handling MIME-Types of enclosures */ public class SyndTypeUtils { private final static String VALID_MIMETYPE = "audio/.*" + "|" + "video/.*" + "|" + "application/ogg"; private SyndTypeUtils() { } public static boolean typeValid(String type) { return type.matches(VALID_MIMETYPE); } /** * Should be used if mime-type of enclosure tag is not supported. This * method will check if the mime-type of the file extension is supported. If * the type is not supported, this method will return null. */ public static String getValidMimeTypeFromUrl(String url) { String extension = FilenameUtils.getExtension(url); if (extension != null) { String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension( extension); - if (typeValid(type)) { + if (type != null && typeValid(type)) { return type; } } return null; } }
true
true
public static String getValidMimeTypeFromUrl(String url) { String extension = FilenameUtils.getExtension(url); if (extension != null) { String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension( extension); if (typeValid(type)) { return type; } } return null; }
public static String getValidMimeTypeFromUrl(String url) { String extension = FilenameUtils.getExtension(url); if (extension != null) { String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension( extension); if (type != null && typeValid(type)) { return type; } } return null; }
diff --git a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java index a64f359..d6d27b1 100644 --- a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java +++ b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java @@ -1,207 +1,207 @@ package com.tihiy.rclint.implement; import com.tihiy.rclint.control.Controller; import com.tihiy.rclint.mvcAbstract.AbstractViewPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class ControlPanel extends AbstractViewPanel { private final Controller mc; private File defaultPath; private File sourceFile; public ControlPanel(Controller mc) { this.mc = mc; setBorder(BorderFactory.createLineBorder(Color.BLUE)); setLayout(new GridBagLayout()); initComponent(); } private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { - e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + e1.printStackTrace(); //change body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); } @Override public void modelPropertyChange(PropertyChangeEvent evt) { } private JButton butChooseSignal; private JButton butChooseFirstLayerSignal; private JButton butChooseBaseSignal; private JButton butCalculate; private JButton butDefault; private JTextField mainSizeA; private JTextField mainSizeB; private JTextField mainXShift; private JTextField mainYShift; private JTextField mainRSphere; private JTextField mainH; private JTextField firstSizeA; private JTextField firstSizeB; private File chooseFile(){ JFileChooser fileChooser = new JFileChooser(); fileChooser.changeToParentDirectory(); fileChooser.setCurrentDirectory(new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716")); // defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); if(defaultPath!=null){ fileChooser.setCurrentDirectory( defaultPath); } fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.showDialog(new JFrame(), "Choose signal!"); if(defaultPath==null){ defaultPath = fileChooser.getCurrentDirectory(); } return fileChooser.getSelectedFile(); } private static String getDate(){ Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("_yyyy_MM_dd_hh_mm_ss"); return ft.format(dNow); } private String getComment(File roFile, File baseFile, double[] main, double[] first){ String comment = "Pulse="+sourceFile.getName()+" Ro="+roFile.getName()+" Base="+baseFile.getName()+" "; comment += "pulseES:"; for(double d:main){ comment += " "+d; } comment += " baseES" + first[0]+" "+first[1]+" "; return comment; } }
true
true
private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); }
private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //change body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); }
diff --git a/src/balle/world/BasicWorld.java b/src/balle/world/BasicWorld.java index b8af880..beb2cdd 100644 --- a/src/balle/world/BasicWorld.java +++ b/src/balle/world/BasicWorld.java @@ -1,186 +1,186 @@ package balle.world; import balle.misc.Globals; public class BasicWorld extends AbstractWorld { private Snapshot prev = null; private double pitchWidth = -1; private double pitchHeight = -1; public BasicWorld(boolean balleIsBlue) { super(balleIsBlue); } @Override public synchronized Snapshot getSnapshot() { return prev; } private Coord subtractOrNull(Coord a, Coord b) { if ((a == null) || (b == null)) return null; else return a.sub(b); } protected double scaleXToMeters(double x) { if (x < 0) return x; return (x / pitchWidth) * Globals.PITCH_WIDTH; } protected double scaleYToMeters(double y) { if (y < 0) return y; return (y / pitchHeight) * Globals.PITCH_HEIGHT; } /** * NOTE: DO ROBOTS ALWAYS MOVE FORWARD !? NO, treat angle of velocity * different from angle the robot is facing. * */ @Override public void update(double yPosX, double yPosY, double yRad, double bPosX, double bPosY, double bRad, double ballPosX, double ballPosY, long timestamp) { if ((pitchWidth < 0) || (pitchHeight < 0)) { System.err .println("Cannot update locations as pitch size is not set properly. Restart vision"); return; } // Scale the coordinates from vision to meters: yPosX = scaleXToMeters(yPosX); yPosY = scaleXToMeters(yPosY); bPosX = scaleXToMeters(bPosX); bPosY = scaleXToMeters(bPosY); ballPosX = scaleXToMeters(ballPosX); ballPosY = scaleXToMeters(ballPosY); Robot ours = null; Robot them = null; FieldObject ball = null; // Coordinates Coord ourPosition, theirsPosition; Orientation ourOrientation; // Orientations Orientation theirsOrientation; // Adjust based on our color. if (isBlue()) { if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(bPosX, bPosY); ourOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(yPosX, yPosY); theirsOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; } else { if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(yPosX, yPosY); ourOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(bPosX, bPosY); theirsOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; } Coord ballPosition; // Ball position - if ((bPosX - UNKNOWN_VALUE < 0.00001) - || (bPosY - UNKNOWN_VALUE < 0.00001)) + if ((ballPosX - UNKNOWN_VALUE < 0.00001) + || (ballPosY - UNKNOWN_VALUE < 0.00001)) ballPosition = null; else ballPosition = new Coord(ballPosX, ballPosY); Snapshot prev = getSnapshot(); // First case when there is no past snapshot (assume velocities are 0) if (prev == null) { if ((theirsPosition != null) && (theirsOrientation != null)) them = new Robot(theirsPosition, new Velocity(0, 0, 1), theirsOrientation); if ((ourPosition != null) && (ourOrientation != null)) ours = new Robot(ourPosition, new Velocity(0, 0, 1), ourOrientation); if (ballPosition != null) ball = new FieldObject(ballPosition, new Velocity(0, 0, 1)); } else { // change in time long deltaT = timestamp - prev.getTimestamp(); // Special case when we get two inputs with the same timestamp: if (deltaT == 0) { // This will just keep the prev world in the memory, not doing // anything return; } if (ourPosition == null) ourPosition = estimatedPosition(prev.getBalle(), deltaT); if (theirsPosition == null) theirsPosition = estimatedPosition(prev.getOpponent(), deltaT); if (ballPosition == null) ballPosition = estimatedPosition(prev.getBall(), deltaT); // Change in position Coord oursDPos, themDPos, ballDPos; oursDPos = prev.getBalle() != null ? subtractOrNull(ourPosition, prev.getBalle().getPosition()) : null; themDPos = prev.getOpponent() != null ? subtractOrNull( theirsPosition, prev.getOpponent().getPosition()) : null; ballDPos = prev.getBall() != null ? subtractOrNull(ballPosition, prev.getBall().getPosition()) : null; // velocities Velocity oursVel, themVel, ballVel; oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null; themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null; ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null; // put it all together (almost) them = new Robot(theirsPosition, themVel, theirsOrientation); ours = new Robot(ourPosition, oursVel, ourOrientation); ball = new FieldObject(ballPosition, ballVel); } synchronized (this) { // pack into a snapshot this.prev = new Snapshot(them, ours, ball, timestamp); } } @Override public void updatePitchSize(double width, double height) { prev = null; pitchWidth = width; pitchHeight = height; } }
true
true
public void update(double yPosX, double yPosY, double yRad, double bPosX, double bPosY, double bRad, double ballPosX, double ballPosY, long timestamp) { if ((pitchWidth < 0) || (pitchHeight < 0)) { System.err .println("Cannot update locations as pitch size is not set properly. Restart vision"); return; } // Scale the coordinates from vision to meters: yPosX = scaleXToMeters(yPosX); yPosY = scaleXToMeters(yPosY); bPosX = scaleXToMeters(bPosX); bPosY = scaleXToMeters(bPosY); ballPosX = scaleXToMeters(ballPosX); ballPosY = scaleXToMeters(ballPosY); Robot ours = null; Robot them = null; FieldObject ball = null; // Coordinates Coord ourPosition, theirsPosition; Orientation ourOrientation; // Orientations Orientation theirsOrientation; // Adjust based on our color. if (isBlue()) { if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(bPosX, bPosY); ourOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(yPosX, yPosY); theirsOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; } else { if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(yPosX, yPosY); ourOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(bPosX, bPosY); theirsOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; } Coord ballPosition; // Ball position if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) ballPosition = null; else ballPosition = new Coord(ballPosX, ballPosY); Snapshot prev = getSnapshot(); // First case when there is no past snapshot (assume velocities are 0) if (prev == null) { if ((theirsPosition != null) && (theirsOrientation != null)) them = new Robot(theirsPosition, new Velocity(0, 0, 1), theirsOrientation); if ((ourPosition != null) && (ourOrientation != null)) ours = new Robot(ourPosition, new Velocity(0, 0, 1), ourOrientation); if (ballPosition != null) ball = new FieldObject(ballPosition, new Velocity(0, 0, 1)); } else { // change in time long deltaT = timestamp - prev.getTimestamp(); // Special case when we get two inputs with the same timestamp: if (deltaT == 0) { // This will just keep the prev world in the memory, not doing // anything return; } if (ourPosition == null) ourPosition = estimatedPosition(prev.getBalle(), deltaT); if (theirsPosition == null) theirsPosition = estimatedPosition(prev.getOpponent(), deltaT); if (ballPosition == null) ballPosition = estimatedPosition(prev.getBall(), deltaT); // Change in position Coord oursDPos, themDPos, ballDPos; oursDPos = prev.getBalle() != null ? subtractOrNull(ourPosition, prev.getBalle().getPosition()) : null; themDPos = prev.getOpponent() != null ? subtractOrNull( theirsPosition, prev.getOpponent().getPosition()) : null; ballDPos = prev.getBall() != null ? subtractOrNull(ballPosition, prev.getBall().getPosition()) : null; // velocities Velocity oursVel, themVel, ballVel; oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null; themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null; ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null; // put it all together (almost) them = new Robot(theirsPosition, themVel, theirsOrientation); ours = new Robot(ourPosition, oursVel, ourOrientation); ball = new FieldObject(ballPosition, ballVel); } synchronized (this) { // pack into a snapshot this.prev = new Snapshot(them, ours, ball, timestamp); } }
public void update(double yPosX, double yPosY, double yRad, double bPosX, double bPosY, double bRad, double ballPosX, double ballPosY, long timestamp) { if ((pitchWidth < 0) || (pitchHeight < 0)) { System.err .println("Cannot update locations as pitch size is not set properly. Restart vision"); return; } // Scale the coordinates from vision to meters: yPosX = scaleXToMeters(yPosX); yPosY = scaleXToMeters(yPosY); bPosX = scaleXToMeters(bPosX); bPosY = scaleXToMeters(bPosY); ballPosX = scaleXToMeters(ballPosX); ballPosY = scaleXToMeters(ballPosY); Robot ours = null; Robot them = null; FieldObject ball = null; // Coordinates Coord ourPosition, theirsPosition; Orientation ourOrientation; // Orientations Orientation theirsOrientation; // Adjust based on our color. if (isBlue()) { if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(bPosX, bPosY); ourOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(yPosX, yPosY); theirsOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; } else { if ((yPosX - UNKNOWN_VALUE < 0.00001) || (yPosY - UNKNOWN_VALUE < 0.00001)) ourPosition = null; else ourPosition = new Coord(yPosX, yPosY); ourOrientation = (yRad != UNKNOWN_VALUE) ? new Orientation(yRad, false) : null; if ((bPosX - UNKNOWN_VALUE < 0.00001) || (bPosY - UNKNOWN_VALUE < 0.00001)) theirsPosition = null; else theirsPosition = new Coord(bPosX, bPosY); theirsOrientation = (bRad != UNKNOWN_VALUE) ? new Orientation(bRad, false) : null; } Coord ballPosition; // Ball position if ((ballPosX - UNKNOWN_VALUE < 0.00001) || (ballPosY - UNKNOWN_VALUE < 0.00001)) ballPosition = null; else ballPosition = new Coord(ballPosX, ballPosY); Snapshot prev = getSnapshot(); // First case when there is no past snapshot (assume velocities are 0) if (prev == null) { if ((theirsPosition != null) && (theirsOrientation != null)) them = new Robot(theirsPosition, new Velocity(0, 0, 1), theirsOrientation); if ((ourPosition != null) && (ourOrientation != null)) ours = new Robot(ourPosition, new Velocity(0, 0, 1), ourOrientation); if (ballPosition != null) ball = new FieldObject(ballPosition, new Velocity(0, 0, 1)); } else { // change in time long deltaT = timestamp - prev.getTimestamp(); // Special case when we get two inputs with the same timestamp: if (deltaT == 0) { // This will just keep the prev world in the memory, not doing // anything return; } if (ourPosition == null) ourPosition = estimatedPosition(prev.getBalle(), deltaT); if (theirsPosition == null) theirsPosition = estimatedPosition(prev.getOpponent(), deltaT); if (ballPosition == null) ballPosition = estimatedPosition(prev.getBall(), deltaT); // Change in position Coord oursDPos, themDPos, ballDPos; oursDPos = prev.getBalle() != null ? subtractOrNull(ourPosition, prev.getBalle().getPosition()) : null; themDPos = prev.getOpponent() != null ? subtractOrNull( theirsPosition, prev.getOpponent().getPosition()) : null; ballDPos = prev.getBall() != null ? subtractOrNull(ballPosition, prev.getBall().getPosition()) : null; // velocities Velocity oursVel, themVel, ballVel; oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null; themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null; ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null; // put it all together (almost) them = new Robot(theirsPosition, themVel, theirsOrientation); ours = new Robot(ourPosition, oursVel, ourOrientation); ball = new FieldObject(ballPosition, ballVel); } synchronized (this) { // pack into a snapshot this.prev = new Snapshot(them, ours, ball, timestamp); } }
diff --git a/BackupToDropboxV2/src/utils/Connection.java b/BackupToDropboxV2/src/utils/Connection.java index 1918d06..82cd6f8 100644 --- a/BackupToDropboxV2/src/utils/Connection.java +++ b/BackupToDropboxV2/src/utils/Connection.java @@ -1,283 +1,283 @@ package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.Map; import org.apache.commons.logging.Log; import com.dropbox.client2.DropboxAPI; import com.dropbox.client2.DropboxAPI.ChunkedUploader; import com.dropbox.client2.DropboxAPI.Entry; import com.dropbox.client2.exception.DropboxException; import com.dropbox.client2.exception.DropboxServerException; import com.dropbox.client2.exception.DropboxUnlinkedException; import com.dropbox.client2.session.AccessTokenPair; import com.dropbox.client2.session.AppKeyPair; import com.dropbox.client2.session.Session; import com.dropbox.client2.session.WebAuthSession; public class Connection { public static final String STATE_FILE = "state.json"; // ------------------------------------------------------------------------ // Reset state public static void doReset(String appKey, String appScreet) throws DropboxException { AppKeyPair appKeyPair = new AppKeyPair(appKey, appScreet); // Save state State state = new State(appKeyPair); state.save(STATE_FILE); } // ------------------------------------------------------------------------ // Link another account. public static void doLink() throws DropboxException { State state; // Load state. try { state = State.load(STATE_FILE); } catch (Exception ex) { doReset("atpzm7nb23oa2ac", "udqftxi7nfiq553"); state = State.load(STATE_FILE); } WebAuthSession was = new WebAuthSession(state.appKey, Session.AccessType.APP_FOLDER); // Make the user log in and authorize us. WebAuthSession.WebAuthInfo info = was.getAuthInfo(); System.out.println("1. Go to: " + info.url); System.out.println("2. Allow access to this app."); System.out.println("3. Press ENTER."); try { while (System.in.read() != '\n') { } } catch (IOException ex) { throw die("I/O error: " + ex.getMessage()); } // This will fail if the user didn't visit the above URL and hit // 'Allow'. String uid = was.retrieveWebAccessToken(info.requestTokenPair); AccessTokenPair accessToken = was.getAccessTokenPair(); System.out.println("Link successful."); state.links.put(uid, accessToken); state.save(STATE_FILE); } // ------------------------------------------------------------------------ // Link another account. public static void doList() throws DropboxException { // Load state. State state = State.load(STATE_FILE); if (state.links.isEmpty()) { System.out.println("No links."); } else { System.out.println("[uid: access token]"); for (Map.Entry<String, AccessTokenPair> link : state.links .entrySet()) { AccessTokenPair at = link.getValue(); System.out.println(link.getKey() + ": " + at.key + " " + at.secret); } } } // ------------------------------------------------------------------------ // Copy a file public static void doCopy(String[] args) throws DropboxException { if (args.length != 3) { throw die("ERROR: \"copy\" takes exactly two arguments"); } // Load cached state. State state = State.load(STATE_FILE); GlobalPath source, target; try { source = GlobalPath.parse(args[1]); } catch (GlobalPath.FormatException ex) { throw die("ERROR: Bad <source>: " + ex.getMessage()); } try { target = GlobalPath.parse(args[2]); } catch (GlobalPath.FormatException ex) { throw die("ERROR: Bad <source>: " + ex.getMessage()); } AccessTokenPair sourceAccess = state.links.get(source.uid); if (sourceAccess == null) { throw die("ERROR: <source> refers to UID that isn't linked."); } AccessTokenPair targetAccess = state.links.get(target.uid); if (targetAccess == null) { throw die("ERROR: <target> refers to UID that isn't linked."); } // Connect to the <source> UID and create a copy-ref. WebAuthSession sourceSession = new WebAuthSession(state.appKey, Session.AccessType.DROPBOX, sourceAccess); DropboxAPI<?> sourceClient = new DropboxAPI<WebAuthSession>( sourceSession); DropboxAPI.CreatedCopyRef cr = sourceClient.createCopyRef(source.path); // Connect to the <target> UID and add the target file. WebAuthSession targetSession = new WebAuthSession(state.appKey, Session.AccessType.DROPBOX, targetAccess); DropboxAPI<?> targetClient = new DropboxAPI<WebAuthSession>( targetSession); targetClient.addFromCopyRef(cr.copyRef, target.path); System.out.println("Copied."); } // ------------------------------------------------------------------------ // upload a file public static void doUpload(String sourceFile, String TargetFile) { // Load cached state. State state = State.load(STATE_FILE); String linkKey = state.links.entrySet().iterator().next().getKey(); AccessTokenPair targetAccess = state.links.get(linkKey); if (targetAccess == null) { throw die("ERROR: <source> refers to UID that isn't linked."); } WebAuthSession session = new WebAuthSession(state.appKey, Session.AccessType.APP_FOLDER, targetAccess); DropboxAPI<?> client = new DropboxAPI<WebAuthSession>(session); FileInputStream inputStream = null; try { File file = new File(sourceFile); inputStream = new FileInputStream(file); Entry newEntry = client.putFile(TargetFile, inputStream, file.length(), null, null); System.out.println("The uploaded file's rev is: " + newEntry.rev); } catch (DropboxUnlinkedException e) { // User has unlinked, ask them to link again here. System.out.println("User has unlinked."); } catch (DropboxException e) { System.out.println("Something went wrong while uploading."); } catch (FileNotFoundException e) { System.out.println("File not found."); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } // ------------------------------------------------------------------------ // upload bigger files public static void doChunkUpload(String sourceFile) { // Load cached state. State state = State.load(STATE_FILE); String linkKey = state.links.entrySet().iterator().next().getKey(); AccessTokenPair targetAccess = state.links.get(linkKey); if (targetAccess == null) { throw die("ERROR: <source> refers to UID that isn't linked."); } WebAuthSession session = new WebAuthSession(state.appKey, Session.AccessType.APP_FOLDER, targetAccess); DropboxAPI<?> client = new DropboxAPI<WebAuthSession>(session); FileInputStream inputStream = null; try { File file = new File(sourceFile); inputStream = new FileInputStream(file); @SuppressWarnings("rawtypes") ChunkedUploader uploader = client.getChunkedUploader( inputStream, file.length()); while (!uploader.isComplete()) { try { uploader.upload(); } catch (IOException e) { e.printStackTrace(); } } if (uploader.isComplete()) { String parentRev = null; try { - Entry metadata = client.metadata(sourceFile, 1, null, false, null); + Entry metadata = client.metadata("/", 0, null, false, null); parentRev = metadata.rev; } catch (DropboxServerException e) { //if (e.error!= DropboxServerException._404_NOT_FOUND) System.err.println(e); } - uploader.finish(sourceFile, parentRev); + uploader.finish(file.getName(), parentRev); System.out.println("File is Uploaded!"); } } catch (DropboxUnlinkedException e) { // User has unlinked, ask them to link again here. System.out.println("User has unlinked."); } catch (DropboxException e) { System.out.println("Something went wrong while uploading."); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println("File not found."); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } // ------------------------------------------------------------------------ public static void printUsage(PrintStream out) { out.println("Usage:"); out.println(" ./run reset <app-key> <secret> Initialize the state with the given app key."); out.println(" ./run link Link an account to this app."); out.println(" ./run list List accounts that have been linked."); out.println(" ./run copy <source> <target> Copy a file; paths are of the form <uid>:<path>."); } public static RuntimeException die(String message) { System.err.println(message); return die(); } public static RuntimeException die() { System.exit(1); return new RuntimeException(); } }
false
true
public static void doChunkUpload(String sourceFile) { // Load cached state. State state = State.load(STATE_FILE); String linkKey = state.links.entrySet().iterator().next().getKey(); AccessTokenPair targetAccess = state.links.get(linkKey); if (targetAccess == null) { throw die("ERROR: <source> refers to UID that isn't linked."); } WebAuthSession session = new WebAuthSession(state.appKey, Session.AccessType.APP_FOLDER, targetAccess); DropboxAPI<?> client = new DropboxAPI<WebAuthSession>(session); FileInputStream inputStream = null; try { File file = new File(sourceFile); inputStream = new FileInputStream(file); @SuppressWarnings("rawtypes") ChunkedUploader uploader = client.getChunkedUploader( inputStream, file.length()); while (!uploader.isComplete()) { try { uploader.upload(); } catch (IOException e) { e.printStackTrace(); } } if (uploader.isComplete()) { String parentRev = null; try { Entry metadata = client.metadata(sourceFile, 1, null, false, null); parentRev = metadata.rev; } catch (DropboxServerException e) { //if (e.error!= DropboxServerException._404_NOT_FOUND) System.err.println(e); } uploader.finish(sourceFile, parentRev); System.out.println("File is Uploaded!"); } } catch (DropboxUnlinkedException e) { // User has unlinked, ask them to link again here. System.out.println("User has unlinked."); } catch (DropboxException e) { System.out.println("Something went wrong while uploading."); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println("File not found."); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } }
public static void doChunkUpload(String sourceFile) { // Load cached state. State state = State.load(STATE_FILE); String linkKey = state.links.entrySet().iterator().next().getKey(); AccessTokenPair targetAccess = state.links.get(linkKey); if (targetAccess == null) { throw die("ERROR: <source> refers to UID that isn't linked."); } WebAuthSession session = new WebAuthSession(state.appKey, Session.AccessType.APP_FOLDER, targetAccess); DropboxAPI<?> client = new DropboxAPI<WebAuthSession>(session); FileInputStream inputStream = null; try { File file = new File(sourceFile); inputStream = new FileInputStream(file); @SuppressWarnings("rawtypes") ChunkedUploader uploader = client.getChunkedUploader( inputStream, file.length()); while (!uploader.isComplete()) { try { uploader.upload(); } catch (IOException e) { e.printStackTrace(); } } if (uploader.isComplete()) { String parentRev = null; try { Entry metadata = client.metadata("/", 0, null, false, null); parentRev = metadata.rev; } catch (DropboxServerException e) { //if (e.error!= DropboxServerException._404_NOT_FOUND) System.err.println(e); } uploader.finish(file.getName(), parentRev); System.out.println("File is Uploaded!"); } } catch (DropboxUnlinkedException e) { // User has unlinked, ask them to link again here. System.out.println("User has unlinked."); } catch (DropboxException e) { System.out.println("Something went wrong while uploading."); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println("File not found."); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/Login.java b/SWADroid/src/es/ugr/swad/swadroid/modules/Login.java index b75f8dea..ad9c351e 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/Login.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/Login.java @@ -1,176 +1,176 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.model.User; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.kobjects.base64.Base64; import org.ksoap2.SoapFault; import org.xmlpull.v1.XmlPullParserException; /** * Login module for connect to SWAD. * @author Juan Miguel Boyero Corral <[email protected]> */ public class Login extends Module { /** * Digest for user password. */ private MessageDigest md; /** * User password. */ private String userPassword; /** * Called when activity is first created. * @param savedInstanceState State of activity. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setMETHOD_NAME("loginByUserPassword"); connect(); } /** * Launches login action in a separate thread while shows a progress dialog * in UI thread. */ private void connect() { new Connect().execute(); } /** * Connects to SWAD and gets user data. * @throws NoSuchAlgorithmException * @throws IOException * @throws XmlPullParserException * @throws SoapFault */ private void requestService() throws NoSuchAlgorithmException, IOException, XmlPullParserException, SoapFault { //Encrypts user password with SHA-512 and encodes it to Base64 md = MessageDigest.getInstance("SHA-512"); md.update(prefs.getUserPassword().getBytes()); userPassword = Base64.encode(md.digest()); //Creates webservice request, adds required params and sends request to webservice createRequest(); addParam("userID", prefs.getUserID()); addParam("userPassword", userPassword); sendRequest(); //Stores user data returned by webservice response - User.setUserCode((String) result.getProperty("userCode")); - User.setUserTypeCode((String) result.getProperty("userTypeCode")); - User.setWsKey((String) result.getProperty("wsKey")); - User.setUserID((String) result.getProperty("userID")); - User.setUserSurname1((String) result.getProperty("userSurname1")); - User.setUserSurname2((String) result.getProperty("userSurname2")); - User.setUserFirstName((String) result.getProperty("userFirstName")); - User.setUserTypeName((String) result.getProperty("userTypeName")); + User.setUserCode(result.getProperty("userCode").toString()); + User.setUserTypeCode(result.getProperty("userTypeCode").toString()); + User.setWsKey(result.getProperty("wsKey").toString()); + User.setUserID(result.getProperty("userID").toString()); + User.setUserSurname1(result.getProperty("userSurname1").toString()); + User.setUserSurname2(result.getProperty("userSurname2").toString()); + User.setUserFirstName(result.getProperty("userFirstName").toString()); + User.setUserTypeName(result.getProperty("userTypeName").toString()); //Request finalized without errors setResult(RESULT_OK); } /** * Shows progress dialog when connecting to SWAD */ private class Connect extends AsyncTask<String, Void, Void> { /** * Progress dialog. */ ProgressDialog Dialog = new ProgressDialog(Login.this); /** * Exception pointer. */ Exception e = null; /** * Called before launch background thread. */ @Override protected void onPreExecute() { Dialog.setMessage(getString(R.string.loginProgressDescription)); Dialog.setTitle(R.string.loginProgressTitle); Dialog.show(); } /** * Called in background thread. * @param urls Background thread parameters. * @return Nothing. */ protected Void doInBackground(String... urls) { try { //Sends webservice request requestService(); /** * If an exception occurs, capture and points exception pointer * to it. */ } catch (SoapFault ex) { e = ex; } catch (Exception ex) { e = ex; } return null; } /** * Called after calling background thread. * @param unused Does nothing. */ @Override protected void onPostExecute(Void unused) { Dialog.dismiss(); if(e != null) { /** * If an exception has occurred, shows error message according to * exception type. */ if(e instanceof SoapFault) { SoapFault es = (SoapFault) e; Log.e(es.getClass().getSimpleName(), es.faultstring); error(es.faultstring); } else { Log.e(e.getClass().getSimpleName(), e.toString()); error(e.toString()); } //Request finalized with errors e.printStackTrace(); setResult(RESULT_CANCELED); } } } }
true
true
private void requestService() throws NoSuchAlgorithmException, IOException, XmlPullParserException, SoapFault { //Encrypts user password with SHA-512 and encodes it to Base64 md = MessageDigest.getInstance("SHA-512"); md.update(prefs.getUserPassword().getBytes()); userPassword = Base64.encode(md.digest()); //Creates webservice request, adds required params and sends request to webservice createRequest(); addParam("userID", prefs.getUserID()); addParam("userPassword", userPassword); sendRequest(); //Stores user data returned by webservice response User.setUserCode((String) result.getProperty("userCode")); User.setUserTypeCode((String) result.getProperty("userTypeCode")); User.setWsKey((String) result.getProperty("wsKey")); User.setUserID((String) result.getProperty("userID")); User.setUserSurname1((String) result.getProperty("userSurname1")); User.setUserSurname2((String) result.getProperty("userSurname2")); User.setUserFirstName((String) result.getProperty("userFirstName")); User.setUserTypeName((String) result.getProperty("userTypeName")); //Request finalized without errors setResult(RESULT_OK); }
private void requestService() throws NoSuchAlgorithmException, IOException, XmlPullParserException, SoapFault { //Encrypts user password with SHA-512 and encodes it to Base64 md = MessageDigest.getInstance("SHA-512"); md.update(prefs.getUserPassword().getBytes()); userPassword = Base64.encode(md.digest()); //Creates webservice request, adds required params and sends request to webservice createRequest(); addParam("userID", prefs.getUserID()); addParam("userPassword", userPassword); sendRequest(); //Stores user data returned by webservice response User.setUserCode(result.getProperty("userCode").toString()); User.setUserTypeCode(result.getProperty("userTypeCode").toString()); User.setWsKey(result.getProperty("wsKey").toString()); User.setUserID(result.getProperty("userID").toString()); User.setUserSurname1(result.getProperty("userSurname1").toString()); User.setUserSurname2(result.getProperty("userSurname2").toString()); User.setUserFirstName(result.getProperty("userFirstName").toString()); User.setUserTypeName(result.getProperty("userTypeName").toString()); //Request finalized without errors setResult(RESULT_OK); }
diff --git a/app/src/processing/app/syntax/PdeKeywords.java b/app/src/processing/app/syntax/PdeKeywords.java index 9b5ea6838..e9b29f1ff 100644 --- a/app/src/processing/app/syntax/PdeKeywords.java +++ b/app/src/processing/app/syntax/PdeKeywords.java @@ -1,257 +1,258 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* PdeKeywords - handles text coloring and links to html reference Part of the Processing project - http://processing.org Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app.syntax; import javax.swing.text.Segment; import processing.app.Editor; /** * This class reads a keywords.txt file to get coloring put links to reference * locations for the set of keywords. */ public class PdeKeywords extends TokenMarker { private KeywordMap keywordColoring; private int lastOffset; private int lastKeyword; /** * Add a keyword, and the associated coloring. KEYWORD2 and KEYWORD3 * should only be used with functions (where parens are present). * This is done for the extra paren handling. * @param coloring one of KEYWORD1, KEYWORD2, LITERAL1, etc. */ public void addColoring(String keyword, String coloring) { if (keywordColoring == null) { keywordColoring = new KeywordMap(false); } // KEYWORD1 -> 0, KEYWORD2 -> 1, etc int num = coloring.charAt(coloring.length() - 1) - '1'; // byte id = (byte) ((isKey ? Token.KEYWORD1 : Token.LITERAL1) + num); int id = 0; boolean paren = false; switch (coloring.charAt(0)) { case 'K': id = Token.KEYWORD1 + num; break; case 'L': id = Token.LITERAL1 + num; break; case 'F': id = Token.FUNCTION1 + num; paren = true; break; } keywordColoring.add(keyword, (byte) id, paren); } public byte markTokensImpl(byte token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; lastOffset = offset; lastKeyword = offset; int mlength = offset + line.count; boolean backslash = false; loop: for (int i = offset; i < mlength; i++) { int i1 = (i + 1); char c = array[i]; if (c == '\\') { backslash = !backslash; continue; } switch (token) { case Token.NULL: switch (c) { case '#': if (backslash) backslash = false; break; case '"': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL1; lastOffset = lastKeyword = i; } break; case '\'': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL2; lastOffset = lastKeyword = i; } break; case ':': if (lastKeyword == offset) { if (doKeyword(line, i, c)) break; backslash = false; addToken(i1 - lastOffset, Token.LABEL); lastOffset = lastKeyword = i1; } else if (doKeyword(line, i, c)) break; break; case '/': backslash = false; doKeyword(line, i, c); if (mlength - i > 1) { switch (array[i1]) { case '*': addToken(i - lastOffset, token); lastOffset = lastKeyword = i; if (mlength - i > 2 && array[i + 2] == '*') token = Token.COMMENT2; else token = Token.COMMENT1; break; case '/': addToken(i - lastOffset, token); addToken(mlength - i, Token.COMMENT1); lastOffset = lastKeyword = mlength; break loop; } - i++; // http://processing.org/bugs/bugzilla/609.html [jdf] + if(array[i1]!=' ') + i++; // http://processing.org/bugs/bugzilla/609.html [jdf] } break; default: backslash = false; if (!Character.isLetterOrDigit(c) && c != '_') { // if (i1 < mlength && array[i1] // boolean paren = false; // int stepper = i + 1; // while (stepper < mlength) { // if (array[stepper] == '(') { // paren = true; // break; // } // stepper++; // } doKeyword(line, i, c); // doKeyword(line, i, checkParen(array, i1, mlength)); } break; } break; case Token.COMMENT1: case Token.COMMENT2: backslash = false; if (c == '*' && mlength - i > 1) { if (array[i1] == '/') { i++; addToken((i + 1) - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i + 1; } } break; case Token.LITERAL1: if (backslash) backslash = false; else if (c == '"') { addToken(i1 - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.LITERAL2: if (backslash) backslash = false; else if (c == '\'') { addToken(i1 - lastOffset, Token.LITERAL1); token = Token.NULL; lastOffset = lastKeyword = i1; } break; default: throw new InternalError("Invalid state: " + token); } } if (token == Token.NULL) { doKeyword(line, mlength, '\0'); } switch (token) { case Token.LITERAL1: case Token.LITERAL2: addToken(mlength - lastOffset, Token.INVALID); token = Token.NULL; break; case Token.KEYWORD2: addToken(mlength - lastOffset, token); if (!backslash) token = Token.NULL; addToken(mlength - lastOffset, token); break; default: addToken(mlength - lastOffset, token); break; } return token; } private boolean doKeyword(Segment line, int i, char c) { // return doKeyword(line, i, false); // } // // // //private boolean doKeyword(Segment line, int i, char c) { // private boolean doKeyword(Segment line, int i, boolean paren) { int i1 = i + 1; int len = i - lastKeyword; boolean paren = Editor.checkParen(line.array, i, line.array.length); // String s = new String(line.array, lastKeyword, len); // if (s.equals("mousePressed")) { // System.out.println("found mousePressed" + (paren ? "()" : "")); // //new Exception().printStackTrace(System.out); //// System.out.println(" " + i + " " + line.count + " " + //// //new String(line.array, line.offset + i, line.offset + line.count - i)); //// new String(line.array, i, line.array.length - i)); // } byte id = keywordColoring.lookup(line, lastKeyword, len, paren); if (id != Token.NULL) { if (lastKeyword != lastOffset) { addToken(lastKeyword - lastOffset, Token.NULL); } // if (paren && id == Token.LITERAL2) { // id = Token.KEYWORD2; // } else if (!paren && id == Token.KEYWORD2) { // id = Token.LITERAL2; // } addToken(len, id); lastOffset = i; } lastKeyword = i1; return false; } }
true
true
public byte markTokensImpl(byte token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; lastOffset = offset; lastKeyword = offset; int mlength = offset + line.count; boolean backslash = false; loop: for (int i = offset; i < mlength; i++) { int i1 = (i + 1); char c = array[i]; if (c == '\\') { backslash = !backslash; continue; } switch (token) { case Token.NULL: switch (c) { case '#': if (backslash) backslash = false; break; case '"': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL1; lastOffset = lastKeyword = i; } break; case '\'': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL2; lastOffset = lastKeyword = i; } break; case ':': if (lastKeyword == offset) { if (doKeyword(line, i, c)) break; backslash = false; addToken(i1 - lastOffset, Token.LABEL); lastOffset = lastKeyword = i1; } else if (doKeyword(line, i, c)) break; break; case '/': backslash = false; doKeyword(line, i, c); if (mlength - i > 1) { switch (array[i1]) { case '*': addToken(i - lastOffset, token); lastOffset = lastKeyword = i; if (mlength - i > 2 && array[i + 2] == '*') token = Token.COMMENT2; else token = Token.COMMENT1; break; case '/': addToken(i - lastOffset, token); addToken(mlength - i, Token.COMMENT1); lastOffset = lastKeyword = mlength; break loop; } i++; // http://processing.org/bugs/bugzilla/609.html [jdf] } break; default: backslash = false; if (!Character.isLetterOrDigit(c) && c != '_') { // if (i1 < mlength && array[i1] // boolean paren = false; // int stepper = i + 1; // while (stepper < mlength) { // if (array[stepper] == '(') { // paren = true; // break; // } // stepper++; // } doKeyword(line, i, c); // doKeyword(line, i, checkParen(array, i1, mlength)); } break; } break; case Token.COMMENT1: case Token.COMMENT2: backslash = false; if (c == '*' && mlength - i > 1) { if (array[i1] == '/') { i++; addToken((i + 1) - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i + 1; } } break; case Token.LITERAL1: if (backslash) backslash = false; else if (c == '"') { addToken(i1 - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.LITERAL2: if (backslash) backslash = false; else if (c == '\'') { addToken(i1 - lastOffset, Token.LITERAL1); token = Token.NULL; lastOffset = lastKeyword = i1; } break; default: throw new InternalError("Invalid state: " + token); } } if (token == Token.NULL) { doKeyword(line, mlength, '\0'); } switch (token) { case Token.LITERAL1: case Token.LITERAL2: addToken(mlength - lastOffset, Token.INVALID); token = Token.NULL; break; case Token.KEYWORD2: addToken(mlength - lastOffset, token); if (!backslash) token = Token.NULL; addToken(mlength - lastOffset, token); break; default: addToken(mlength - lastOffset, token); break; } return token; }
public byte markTokensImpl(byte token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; lastOffset = offset; lastKeyword = offset; int mlength = offset + line.count; boolean backslash = false; loop: for (int i = offset; i < mlength; i++) { int i1 = (i + 1); char c = array[i]; if (c == '\\') { backslash = !backslash; continue; } switch (token) { case Token.NULL: switch (c) { case '#': if (backslash) backslash = false; break; case '"': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL1; lastOffset = lastKeyword = i; } break; case '\'': doKeyword(line, i, c); if (backslash) backslash = false; else { addToken(i - lastOffset, token); token = Token.LITERAL2; lastOffset = lastKeyword = i; } break; case ':': if (lastKeyword == offset) { if (doKeyword(line, i, c)) break; backslash = false; addToken(i1 - lastOffset, Token.LABEL); lastOffset = lastKeyword = i1; } else if (doKeyword(line, i, c)) break; break; case '/': backslash = false; doKeyword(line, i, c); if (mlength - i > 1) { switch (array[i1]) { case '*': addToken(i - lastOffset, token); lastOffset = lastKeyword = i; if (mlength - i > 2 && array[i + 2] == '*') token = Token.COMMENT2; else token = Token.COMMENT1; break; case '/': addToken(i - lastOffset, token); addToken(mlength - i, Token.COMMENT1); lastOffset = lastKeyword = mlength; break loop; } if(array[i1]!=' ') i++; // http://processing.org/bugs/bugzilla/609.html [jdf] } break; default: backslash = false; if (!Character.isLetterOrDigit(c) && c != '_') { // if (i1 < mlength && array[i1] // boolean paren = false; // int stepper = i + 1; // while (stepper < mlength) { // if (array[stepper] == '(') { // paren = true; // break; // } // stepper++; // } doKeyword(line, i, c); // doKeyword(line, i, checkParen(array, i1, mlength)); } break; } break; case Token.COMMENT1: case Token.COMMENT2: backslash = false; if (c == '*' && mlength - i > 1) { if (array[i1] == '/') { i++; addToken((i + 1) - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i + 1; } } break; case Token.LITERAL1: if (backslash) backslash = false; else if (c == '"') { addToken(i1 - lastOffset, token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.LITERAL2: if (backslash) backslash = false; else if (c == '\'') { addToken(i1 - lastOffset, Token.LITERAL1); token = Token.NULL; lastOffset = lastKeyword = i1; } break; default: throw new InternalError("Invalid state: " + token); } } if (token == Token.NULL) { doKeyword(line, mlength, '\0'); } switch (token) { case Token.LITERAL1: case Token.LITERAL2: addToken(mlength - lastOffset, Token.INVALID); token = Token.NULL; break; case Token.KEYWORD2: addToken(mlength - lastOffset, token); if (!backslash) token = Token.NULL; addToken(mlength - lastOffset, token); break; default: addToken(mlength - lastOffset, token); break; } return token; }
diff --git a/OpenLocation/src/de/h3ndrik/openlocation/LocationReceiver.java b/OpenLocation/src/de/h3ndrik/openlocation/LocationReceiver.java index e413bd2..b2a411d 100644 --- a/OpenLocation/src/de/h3ndrik/openlocation/LocationReceiver.java +++ b/OpenLocation/src/de/h3ndrik/openlocation/LocationReceiver.java @@ -1,172 +1,172 @@ package de.h3ndrik.openlocation; import de.h3ndrik.openlocation.util.Utils; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.location.LocationListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; public class LocationReceiver extends BroadcastReceiver { private static final String DEBUG_TAG = "LocationReceiver"; // for logging purposes private static LocationListener locationListener = null; @Override public void onReceive(Context context, Intent intent) { Log.d(DEBUG_TAG, "got a Broadcast"); if (intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)) { Location location = (Location) intent.getExtras().get( LocationManager.KEY_LOCATION_CHANGED); Log.d(DEBUG_TAG, "location update by " + location.getProvider()); // Toast.makeText(context, "Location changed : Lat: " + // location.getLatitude() + " Long: " + location.getLongitude(), // Toast.LENGTH_SHORT).show(); // write to SQLite DBAdapter db = new DBAdapter(context); db.dbhelper.open_w(); db.dbhelper.insertLocation(location.getTime(), location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy(), location.getSpeed(), location.getBearing(), location.getProvider()); db.dbhelper.close(); } if (intent.hasExtra("de.h3ndrik.openlocation.cancelgps")) { Log.d(DEBUG_TAG, "cancel GPS"); cancelUpdates(context); } } public static void doActiveUpdate(final Context context, Boolean useGPS) { Log.d(DEBUG_TAG, "force active location update"); if (locationListener == null) { Log.d(DEBUG_TAG, "set up new LocationListener"); locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.d(DEBUG_TAG, "locationListener: location changed. disabling myself"); LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); // give location provider time to settle try { Thread.sleep(4000); } catch (InterruptedException e) { // continue } - locationManager.removeUpdates(locationListener); + locationManager.removeUpdates(this); locationListener = null; } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); SharedPreferences SP = PreferenceManager .getDefaultSharedPreferences(context); if (SP.getBoolean("activeupdate", false) && useGPS) { // We want active lookup if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d(DEBUG_TAG, "GPS disabled, requesting network location update"); Toast.makeText( context, context.getResources().getString( R.string.msg_gpsdisabled), Toast.LENGTH_SHORT).show(); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } else { Log.d(DEBUG_TAG, "requesting GPS location update"); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); // workaround, // requestSingleUpdate: only // API Versions >= 9 } } else { // TODO: or do nothing active here? Log.d(DEBUG_TAG, "Active lookup disabled, requesting network location update"); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } /* cancel updates after timeout with no fix */ AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, LocationReceiver.class); i.putExtra("de.h3ndrik.openlocation.cancelgps", "true"); PendingIntent pendingIntent = PendingIntent .getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 16000, pendingIntent); Log.d(DEBUG_TAG, "cancelUpdates alarm set"); } else { Log.d(DEBUG_TAG, "conflicting locationListener, skipping"); } } public static void cancelUpdates(final Context context) { if (locationListener != null) { Log.d(DEBUG_TAG, "removing locationListener"); LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(locationListener); locationListener = null; // Do network lookup instead LocationReceiver.doActiveUpdate(context, false); } else { Log.d(DEBUG_TAG, "no locationListener present"); } } public LocationReceiver() { } }
true
true
public static void doActiveUpdate(final Context context, Boolean useGPS) { Log.d(DEBUG_TAG, "force active location update"); if (locationListener == null) { Log.d(DEBUG_TAG, "set up new LocationListener"); locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.d(DEBUG_TAG, "locationListener: location changed. disabling myself"); LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); // give location provider time to settle try { Thread.sleep(4000); } catch (InterruptedException e) { // continue } locationManager.removeUpdates(locationListener); locationListener = null; } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); SharedPreferences SP = PreferenceManager .getDefaultSharedPreferences(context); if (SP.getBoolean("activeupdate", false) && useGPS) { // We want active lookup if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d(DEBUG_TAG, "GPS disabled, requesting network location update"); Toast.makeText( context, context.getResources().getString( R.string.msg_gpsdisabled), Toast.LENGTH_SHORT).show(); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } else { Log.d(DEBUG_TAG, "requesting GPS location update"); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); // workaround, // requestSingleUpdate: only // API Versions >= 9 } } else { // TODO: or do nothing active here? Log.d(DEBUG_TAG, "Active lookup disabled, requesting network location update"); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } /* cancel updates after timeout with no fix */ AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, LocationReceiver.class); i.putExtra("de.h3ndrik.openlocation.cancelgps", "true"); PendingIntent pendingIntent = PendingIntent .getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 16000, pendingIntent); Log.d(DEBUG_TAG, "cancelUpdates alarm set"); } else { Log.d(DEBUG_TAG, "conflicting locationListener, skipping"); } }
public static void doActiveUpdate(final Context context, Boolean useGPS) { Log.d(DEBUG_TAG, "force active location update"); if (locationListener == null) { Log.d(DEBUG_TAG, "set up new LocationListener"); locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.d(DEBUG_TAG, "locationListener: location changed. disabling myself"); LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); // give location provider time to settle try { Thread.sleep(4000); } catch (InterruptedException e) { // continue } locationManager.removeUpdates(this); locationListener = null; } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); SharedPreferences SP = PreferenceManager .getDefaultSharedPreferences(context); if (SP.getBoolean("activeupdate", false) && useGPS) { // We want active lookup if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d(DEBUG_TAG, "GPS disabled, requesting network location update"); Toast.makeText( context, context.getResources().getString( R.string.msg_gpsdisabled), Toast.LENGTH_SHORT).show(); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } else { Log.d(DEBUG_TAG, "requesting GPS location update"); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); // workaround, // requestSingleUpdate: only // API Versions >= 9 } } else { // TODO: or do nothing active here? Log.d(DEBUG_TAG, "Active lookup disabled, requesting network location update"); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } /* cancel updates after timeout with no fix */ AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, LocationReceiver.class); i.putExtra("de.h3ndrik.openlocation.cancelgps", "true"); PendingIntent pendingIntent = PendingIntent .getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 16000, pendingIntent); Log.d(DEBUG_TAG, "cancelUpdates alarm set"); } else { Log.d(DEBUG_TAG, "conflicting locationListener, skipping"); } }
diff --git a/src/com/dmdirc/addons/osdplugin/OsdWindow.java b/src/com/dmdirc/addons/osdplugin/OsdWindow.java index 275befbe8..961e2c123 100644 --- a/src/com/dmdirc/addons/osdplugin/OsdWindow.java +++ b/src/com/dmdirc/addons/osdplugin/OsdWindow.java @@ -1,145 +1,145 @@ /* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.osdplugin; import com.dmdirc.Config; import com.dmdirc.ui.MainFrame; import static com.dmdirc.ui.UIUtilities.LARGE_BORDER; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Timer; import java.util.TimerTask; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.border.LineBorder; /** * The OSD Window is an always-on-top window designed to convey information * about events to the user. * @author chris */ public final class OsdWindow extends JDialog implements MouseListener, MouseMotionListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 2; /** * Creates a new instance of OsdWindow. * @param text The text to be displayed in the OSD window * @param config Is the window being configured (should it timeout and * allow itself to be moved) */ public OsdWindow(final String text, final boolean config) { super(MainFrame.getMainFrame(), false); setFocusableWindowState(false); setAlwaysOnTop(true); setSize(new Dimension(500, - Config.getOptionInt("plugin-OSD", "fontsize", 20) + LARGE_BORDER)); + Config.getOptionInt("plugin-OSD", "fontSize", 20) + LARGE_BORDER)); setResizable(false); setUndecorated(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLocation(Config.getOptionInt("plugin-OSD", "locationX", 20), Config.getOptionInt("plugin-OSD", "locationY", 20)); final JPanel panel = new JPanel(); panel.setBorder(new LineBorder(Color.BLACK)); panel.setBackground(Config.getOptionColor("plugin-OSD", "bgcolour", Color.decode("#2222aa"))); setContentPane(panel); setLayout(new BorderLayout()); final JLabel label = new JLabel(text); label.setForeground(Config.getOptionColor("plugin-OSD", "fgcolour", Color.decode("#ffffff"))); label.setFont(label.getFont().deriveFont((float) Config.getOptionInt("plugin-OSD", - "fontsize", 20))); + "fontSize", 20))); label.setHorizontalAlignment(SwingConstants.CENTER); add(label); setVisible(true); if (config) { this.addMouseMotionListener(this); } else { addMouseListener(this); new Timer().schedule(new TimerTask() { public void run() { setVisible(false); } }, Config.getOptionInt("plugin-OSD", "timeout", 15) * 1000); } } /** {@inheritDoc} */ public void mouseClicked(final MouseEvent e) { setVisible(false); } /** {@inheritDoc} */ public void mousePressed(final MouseEvent e) { // Do nothing } /** {@inheritDoc} */ public void mouseReleased(final MouseEvent e) { // Do nothing } /** {@inheritDoc} */ public void mouseEntered(final MouseEvent e) { // Do nothing } /** {@inheritDoc} */ public void mouseExited(final MouseEvent e) { // Do nothing } /** {@inheritDoc} */ public void mouseDragged(final MouseEvent e) { setLocation(e.getLocationOnScreen()); } /** {@inheritDoc} */ public void mouseMoved(final MouseEvent e) { // Do nothing } }
false
true
public OsdWindow(final String text, final boolean config) { super(MainFrame.getMainFrame(), false); setFocusableWindowState(false); setAlwaysOnTop(true); setSize(new Dimension(500, Config.getOptionInt("plugin-OSD", "fontsize", 20) + LARGE_BORDER)); setResizable(false); setUndecorated(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLocation(Config.getOptionInt("plugin-OSD", "locationX", 20), Config.getOptionInt("plugin-OSD", "locationY", 20)); final JPanel panel = new JPanel(); panel.setBorder(new LineBorder(Color.BLACK)); panel.setBackground(Config.getOptionColor("plugin-OSD", "bgcolour", Color.decode("#2222aa"))); setContentPane(panel); setLayout(new BorderLayout()); final JLabel label = new JLabel(text); label.setForeground(Config.getOptionColor("plugin-OSD", "fgcolour", Color.decode("#ffffff"))); label.setFont(label.getFont().deriveFont((float) Config.getOptionInt("plugin-OSD", "fontsize", 20))); label.setHorizontalAlignment(SwingConstants.CENTER); add(label); setVisible(true); if (config) { this.addMouseMotionListener(this); } else { addMouseListener(this); new Timer().schedule(new TimerTask() { public void run() { setVisible(false); } }, Config.getOptionInt("plugin-OSD", "timeout", 15) * 1000); } }
public OsdWindow(final String text, final boolean config) { super(MainFrame.getMainFrame(), false); setFocusableWindowState(false); setAlwaysOnTop(true); setSize(new Dimension(500, Config.getOptionInt("plugin-OSD", "fontSize", 20) + LARGE_BORDER)); setResizable(false); setUndecorated(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLocation(Config.getOptionInt("plugin-OSD", "locationX", 20), Config.getOptionInt("plugin-OSD", "locationY", 20)); final JPanel panel = new JPanel(); panel.setBorder(new LineBorder(Color.BLACK)); panel.setBackground(Config.getOptionColor("plugin-OSD", "bgcolour", Color.decode("#2222aa"))); setContentPane(panel); setLayout(new BorderLayout()); final JLabel label = new JLabel(text); label.setForeground(Config.getOptionColor("plugin-OSD", "fgcolour", Color.decode("#ffffff"))); label.setFont(label.getFont().deriveFont((float) Config.getOptionInt("plugin-OSD", "fontSize", 20))); label.setHorizontalAlignment(SwingConstants.CENTER); add(label); setVisible(true); if (config) { this.addMouseMotionListener(this); } else { addMouseListener(this); new Timer().schedule(new TimerTask() { public void run() { setVisible(false); } }, Config.getOptionInt("plugin-OSD", "timeout", 15) * 1000); } }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java index 4751aaf6..39410c9f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java @@ -1,287 +1,288 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.statusbar.phone; import android.content.Context; import android.content.ContentResolver; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.provider.Settings; import android.util.AttributeSet; import android.util.Slog; import android.view.MotionEvent; import android.view.View; import android.database.ContentObserver; import android.net.Uri; import android.os.Handler; import com.android.systemui.R; import com.android.systemui.statusbar.GestureRecorder; public class NotificationPanelView extends PanelView { private static final float STATUS_BAR_SETTINGS_FLIP_PERCENTAGE_LEFT = 0.85f; private static final float STATUS_BAR_SETTINGS_FLIP_PERCENTAGE_RIGHT = 0.15f; private static final float STATUS_BAR_SETTINGS_LEFT_PERCENTAGE = 0.8f; private static final float STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE = 0.2f; private static final float STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE = 0.05f; private static final float STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE = 0.025f; private static final float STATUS_BAR_SWIPE_MOVE_PERCENTAGE = 0.2f; Drawable mHandleBar; int mHandleBarHeight; View mHandleView; int mFingers; PhoneStatusBar mStatusBar; boolean mOkToFlip; boolean mFastToggleEnabled; int mFastTogglePos; ContentObserver mEnableObserver; ContentObserver mChangeSideObserver; Handler mHandler = new Handler(); private float mGestureStartX; private float mGestureStartY; private float mFlipOffset; private float mSwipeDirection; private boolean mTrackingSwipe; private boolean mSwipeTriggered; public NotificationPanelView(Context context, AttributeSet attrs) { super(context, attrs); } public void setStatusBar(PhoneStatusBar bar) { mStatusBar = bar; } @Override protected void onFinishInflate() { super.onFinishInflate(); Resources resources = getContext().getResources(); mHandleBar = resources.getDrawable(R.drawable.status_bar_close); mHandleBarHeight = resources.getDimensionPixelSize(R.dimen.close_handle_height); mHandleView = findViewById(R.id.handle); setContentDescription(resources.getString( R.string.accessibility_desc_notification_shade)); final ContentResolver resolver = getContext().getContentResolver(); mEnableObserver = new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { mFastToggleEnabled = Settings.System.getBoolean(resolver, Settings.System.FAST_TOGGLE, false); } }; mChangeSideObserver = new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { mFastTogglePos = Settings.System.getInt(resolver, Settings.System.CHOOSE_FASTTOGGLE_SIDE, 1); } }; // Initialization mFastToggleEnabled = Settings.System.getBoolean(resolver, Settings.System.FAST_TOGGLE, false); mFastTogglePos = Settings.System.getInt(resolver, Settings.System.CHOOSE_FASTTOGGLE_SIDE, 1); resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.FAST_TOGGLE), true, mEnableObserver); resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.CHOOSE_FASTTOGGLE_SIDE), true, mChangeSideObserver); } @Override public void fling(float vel, boolean always) { GestureRecorder gr = ((PhoneStatusBarView) mBar).mBar.getGestureRecorder(); if (gr != null) { gr.tag( "fling " + ((vel > 0) ? "open" : "closed"), "notifications,v=" + vel); } super.fling(vel, always); } // We draw the handle ourselves so that it's // always glued to the bottom of the window. @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { final int pl = getPaddingLeft(); final int pr = getPaddingRight(); mHandleBar.setBounds(pl, 0, getWidth() - pr, (int) mHandleBarHeight); } } @Override public void draw(Canvas canvas) { super.draw(canvas); final int off = (int) (getHeight() - mHandleBarHeight - getPaddingBottom()); canvas.translate(0, off); mHandleBar.setState(mHandleView.getDrawableState()); mHandleBar.draw(canvas); canvas.translate(0, -off); } @Override public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; boolean noNotificationPulldown = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_NO_NOTIFICATION_PULLDOWN, 0) == 1; int quickPulldownMode = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (mStatusBar.mHideSettingsPanel) break; mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded(); // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && - quickPulldownMode == 1) { + Settings.System.getInt(getContext().getContentResolver(), + Settings.System.QS_QUICK_PULLDOWN, 0) == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && quickPulldownMode == 2) { flip = true; } else if (!mStatusBar.hasClearableNotifications() && noNotificationPulldown) { flip = true; } break; case MotionEvent.ACTION_MOVE: if (mStatusBar.mHideSettingsPanel) break; final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { mSwipeDirection = event.getX(0) - mGestureStartX; // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for a horizontal, in any direction, to always flip the // views. mSwipeDirection = mSwipeDirection < 0f ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: if (!mStatusBar.mHideSettingsPanel) flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip && !mStatusBar.mHideSettingsPanel) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (getMeasuredHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { // Do not flip if the drag event started within the top bar if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); shouldRecycleEvent = true; } // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; } }
true
true
public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; boolean noNotificationPulldown = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_NO_NOTIFICATION_PULLDOWN, 0) == 1; int quickPulldownMode = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (mStatusBar.mHideSettingsPanel) break; mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded(); // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && quickPulldownMode == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && quickPulldownMode == 2) { flip = true; } else if (!mStatusBar.hasClearableNotifications() && noNotificationPulldown) { flip = true; } break; case MotionEvent.ACTION_MOVE: if (mStatusBar.mHideSettingsPanel) break; final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { mSwipeDirection = event.getX(0) - mGestureStartX; // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for a horizontal, in any direction, to always flip the // views. mSwipeDirection = mSwipeDirection < 0f ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: if (!mStatusBar.mHideSettingsPanel) flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip && !mStatusBar.mHideSettingsPanel) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (getMeasuredHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { // Do not flip if the drag event started within the top bar if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); shouldRecycleEvent = true; } // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; }
public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; boolean noNotificationPulldown = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_NO_NOTIFICATION_PULLDOWN, 0) == 1; int quickPulldownMode = Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (mStatusBar.mHideSettingsPanel) break; mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded(); // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && Settings.System.getInt(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0) == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && quickPulldownMode == 2) { flip = true; } else if (!mStatusBar.hasClearableNotifications() && noNotificationPulldown) { flip = true; } break; case MotionEvent.ACTION_MOVE: if (mStatusBar.mHideSettingsPanel) break; final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { mSwipeDirection = event.getX(0) - mGestureStartX; // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for a horizontal, in any direction, to always flip the // views. mSwipeDirection = mSwipeDirection < 0f ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: if (!mStatusBar.mHideSettingsPanel) flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip && !mStatusBar.mHideSettingsPanel) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (getMeasuredHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { // Do not flip if the drag event started within the top bar if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); shouldRecycleEvent = true; } // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; }
diff --git a/aop/docs/examples/implements/TestInterceptor.java b/aop/docs/examples/implements/TestInterceptor.java index a5cf3e86..aa0ffe99 100644 --- a/aop/docs/examples/implements/TestInterceptor.java +++ b/aop/docs/examples/implements/TestInterceptor.java @@ -1,32 +1,31 @@ /* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ import org.jboss.aop.joinpoint.Invocation; import org.jboss.aop.advice.Interceptor; /** * * @author <a href="mailto:[email protected]">Kabir Khan</a> * @version $Revision: 44138 $ */ public class TestInterceptor implements Interceptor { public String getName() { return "TestInterceptor"; } public Object invoke(Invocation invocation) throws Throwable { try { System.out.println("<<< TestInterceptor intercepting"); - invocation.resolveClassAnnotation(ImplementingInterface.class); return invocation.invokeNext(); } finally { System.out.println(">>> Leaving Trace"); } } }
true
true
public Object invoke(Invocation invocation) throws Throwable { try { System.out.println("<<< TestInterceptor intercepting"); invocation.resolveClassAnnotation(ImplementingInterface.class); return invocation.invokeNext(); } finally { System.out.println(">>> Leaving Trace"); } }
public Object invoke(Invocation invocation) throws Throwable { try { System.out.println("<<< TestInterceptor intercepting"); return invocation.invokeNext(); } finally { System.out.println(">>> Leaving Trace"); } }
diff --git a/src/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java b/src/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java index d26a2b69..d96be927 100644 --- a/src/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java +++ b/src/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java @@ -1,227 +1,227 @@ package test.cli.cloudify.cloud.services.azure; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; import org.apache.commons.io.FileUtils; import org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureException; import org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureRestClient; import org.cloudifysource.esc.driver.provisioning.azure.model.ConfigurationSet; import org.cloudifysource.esc.driver.provisioning.azure.model.ConfigurationSets; import org.cloudifysource.esc.driver.provisioning.azure.model.Deployment; import org.cloudifysource.esc.driver.provisioning.azure.model.Deployments; import org.cloudifysource.esc.driver.provisioning.azure.model.HostedService; import org.cloudifysource.esc.driver.provisioning.azure.model.HostedServices; import org.cloudifysource.esc.driver.provisioning.azure.model.NetworkConfigurationSet; import org.cloudifysource.esc.driver.provisioning.azure.model.Role; import test.cli.cloudify.cloud.services.AbstractCloudService; import com.gigaspaces.webuitf.util.LogUtils; import framework.tools.SGTestHelper; import framework.utils.IOUtils; public class MicrosoftAzureCloudService extends AbstractCloudService { private static final String USER_NAME = System.getProperty("user.name"); private final MicrosoftAzureRestClient azureClient; private static final String AZURE_SUBSCRIPTION_ID = "3226dcf0-3130-42f3-b68f-a2019c09431e"; private static final String PATH_TO_PFX = SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/azure/azure-cert.pfx"; private static final String PFX_PASSWORD = "1408Rokk"; private static final String ADDRESS_SPACE = "10.4.0.0/16"; private static final long ESTIMATED_SHUTDOWN_TIME = 5 * 60 * 1000; private static final long SCAN_INTERVAL = 10 * 1000; // 10 seconds. long time since it takes time to shutdown the machine private static final long SCAN_TIMEOUT = 5 * 60 * 1000; // 5 minutes public MicrosoftAzureCloudService(String uniqueName) { super(uniqueName, "azure"); azureClient = new MicrosoftAzureRestClient(AZURE_SUBSCRIPTION_ID, PATH_TO_PFX, PFX_PASSWORD, null, null, null); } @Override public void injectServiceAuthenticationDetails() throws IOException { copyCustomCloudConfigurationFileToServiceFolder(); copyPrivateKeyToUploadFolder(); final Map<String, String> propsToReplace = new HashMap<String, String>(); propsToReplace.put("cloudify_agent_", this.machinePrefix.toLowerCase() + "cloudify-agent"); propsToReplace.put("cloudify_manager", this.machinePrefix.toLowerCase() + "cloudify-manager"); propsToReplace.put("ENTER_SUBSCRIPTION_ID", AZURE_SUBSCRIPTION_ID); propsToReplace.put("ENTER_USER_NAME", USER_NAME); propsToReplace.put("ENTER_PASSWORD", PFX_PASSWORD); propsToReplace.put("ENTER_AVAILABILITY_SET", USER_NAME); propsToReplace.put("ENTER_DEPLOYMENT_SLOT", "Staging"); propsToReplace.put("ENTER_PFX_FILE", "azure-cert.pfx"); propsToReplace.put("ENTER_PFX_PASSWORD", PFX_PASSWORD); propsToReplace.put("ENTER_VIRTUAL_NETWORK_SITE_NAME", USER_NAME + "networksite"); propsToReplace.put("ENTER_ADDRESS_SPACE", ADDRESS_SPACE); propsToReplace.put("ENTER_AFFINITY_GROUP", USER_NAME + "cloudifyaffinity"); propsToReplace.put("ENTER_LOCATION", "East US"); propsToReplace.put("ENTER_STORAGE_ACCOUNT", USER_NAME + "cloudifystorage"); IOUtils.replaceTextInFile(getPathToCloudGroovy(), propsToReplace); } @Override public String getUser() { return "sgtest"; } @Override public String getApiKey() { throw new UnsupportedOperationException("Microsoft Azure Cloud Driver does not have an API key concept. this method should have never been called"); } @Override public void beforeBootstrap() throws Exception { } @Override public boolean scanLeakedAgentNodes() { return scanNodesWithPrefix("agent"); } @Override public boolean scanLeakedAgentAndManagementNodes() { return scanNodesWithPrefix("agent" , "manager"); } private boolean scanNodesWithPrefix(final String... prefixes) { if (azureClient == null) { LogUtils.log("Microsoft Azure client was not initialized, therefore a bootstrap never took place, and no scan is needed."); return true; } long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT; try { List<String> leakingAgentNodesPublicIps = new ArrayList<String>(); HostedServices listHostedServices = azureClient.listHostedServices(); Deployments deploymentsBeingDeleted = null; do { if (System.currentTimeMillis() > scanEndTime) { - throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted); + throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted.getDeployments()); } Thread.sleep(SCAN_INTERVAL); LogUtils.log("waiting for all deployments to reach a non 'Deleting' state"); for (HostedService hostedService : listHostedServices) { try { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. - if (deployment.getStatus().equals("Deleting")) { + if (deployment.getStatus().toLowerCase().equals("deleting")) { LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus()); deploymentsBeingDeleted = new Deployments(); deploymentsBeingDeleted.getDeployments().add(deployment); } } } catch (MicrosoftAzureException e) { LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage()); } } } while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty())); // now all deployment have reached a steady state. // scan again to find out if there are any agents still running LogUtils.log("scanning all remaining hosted services for running agent nodes"); for (HostedService hostedService : listHostedServices) { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. Role role = deployment.getRoleList().getRoles().get(0); String hostName = role.getRoleName(); // each deployment will have just one role. for (String prefix : prefixes) { if (hostName.contains(prefix)) { String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix); LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName); leakingAgentNodesPublicIps.add(publicIpFromDeployment); } } } } if (!leakingAgentNodesPublicIps.isEmpty()) { for (String ip : leakingAgentNodesPublicIps) { LogUtils.log("attempting to kill agent node : " + ip); long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME; try { azureClient.deleteVirtualMachineByIp(ip, false, endTime); } catch (final Exception e) { LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage()); } } return false; } else { return true; } } catch (final Exception e) { throw new RuntimeException(e); } } private String getPublicIpFromDeployment(Deployment deployment, final String prefix) { String publicIp = null; Role role = deployment.getRoleList().getRoles().get(0); String hostName = role.getRoleName(); if (hostName.contains(prefix)) { ConfigurationSets configurationSets = role.getConfigurationSets(); for (ConfigurationSet configurationSet : configurationSets) { if (configurationSet instanceof NetworkConfigurationSet) { NetworkConfigurationSet networkConfigurationSet = (NetworkConfigurationSet) configurationSet; publicIp = networkConfigurationSet.getInputEndpoints() .getInputEndpoints().get(0).getvIp(); } } } return publicIp; } private void copyCustomCloudConfigurationFileToServiceFolder() throws IOException { // copy custom cloud driver configuration to test folder String cloudServiceFullPath = SGTestHelper.getBuildDir() + "/tools/cli/plugins/esc/" + this.getServiceFolder(); File originalCloudDriverConfigFile = new File(cloudServiceFullPath, "azure-cloud.groovy"); File customCloudDriverConfigFile = new File(SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/azure", "azure-cloud.groovy"); Map<File, File> filesToReplace = new HashMap<File, File>(); filesToReplace.put(originalCloudDriverConfigFile, customCloudDriverConfigFile); if (originalCloudDriverConfigFile.exists()) { originalCloudDriverConfigFile.delete(); } FileUtils.copyFile(customCloudDriverConfigFile, originalCloudDriverConfigFile); } private void copyPrivateKeyToUploadFolder() throws IOException { File pfxFilePath = new File(SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/azure/azure-cert.pfx"); File uploadDir = new File(getPathToCloudFolder() + "/upload"); FileUtils.copyFileToDirectory(pfxFilePath, uploadDir); } }
false
true
private boolean scanNodesWithPrefix(final String... prefixes) { if (azureClient == null) { LogUtils.log("Microsoft Azure client was not initialized, therefore a bootstrap never took place, and no scan is needed."); return true; } long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT; try { List<String> leakingAgentNodesPublicIps = new ArrayList<String>(); HostedServices listHostedServices = azureClient.listHostedServices(); Deployments deploymentsBeingDeleted = null; do { if (System.currentTimeMillis() > scanEndTime) { throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted); } Thread.sleep(SCAN_INTERVAL); LogUtils.log("waiting for all deployments to reach a non 'Deleting' state"); for (HostedService hostedService : listHostedServices) { try { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. if (deployment.getStatus().equals("Deleting")) { LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus()); deploymentsBeingDeleted = new Deployments(); deploymentsBeingDeleted.getDeployments().add(deployment); } } } catch (MicrosoftAzureException e) { LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage()); } } } while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty())); // now all deployment have reached a steady state. // scan again to find out if there are any agents still running LogUtils.log("scanning all remaining hosted services for running agent nodes"); for (HostedService hostedService : listHostedServices) { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. Role role = deployment.getRoleList().getRoles().get(0); String hostName = role.getRoleName(); // each deployment will have just one role. for (String prefix : prefixes) { if (hostName.contains(prefix)) { String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix); LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName); leakingAgentNodesPublicIps.add(publicIpFromDeployment); } } } } if (!leakingAgentNodesPublicIps.isEmpty()) { for (String ip : leakingAgentNodesPublicIps) { LogUtils.log("attempting to kill agent node : " + ip); long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME; try { azureClient.deleteVirtualMachineByIp(ip, false, endTime); } catch (final Exception e) { LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage()); } } return false; } else { return true; } } catch (final Exception e) { throw new RuntimeException(e); } }
private boolean scanNodesWithPrefix(final String... prefixes) { if (azureClient == null) { LogUtils.log("Microsoft Azure client was not initialized, therefore a bootstrap never took place, and no scan is needed."); return true; } long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT; try { List<String> leakingAgentNodesPublicIps = new ArrayList<String>(); HostedServices listHostedServices = azureClient.listHostedServices(); Deployments deploymentsBeingDeleted = null; do { if (System.currentTimeMillis() > scanEndTime) { throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted.getDeployments()); } Thread.sleep(SCAN_INTERVAL); LogUtils.log("waiting for all deployments to reach a non 'Deleting' state"); for (HostedService hostedService : listHostedServices) { try { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. if (deployment.getStatus().toLowerCase().equals("deleting")) { LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus()); deploymentsBeingDeleted = new Deployments(); deploymentsBeingDeleted.getDeployments().add(deployment); } } } catch (MicrosoftAzureException e) { LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage()); } } } while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty())); // now all deployment have reached a steady state. // scan again to find out if there are any agents still running LogUtils.log("scanning all remaining hosted services for running agent nodes"); for (HostedService hostedService : listHostedServices) { List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments(); if (deploymentsForHostedSerice.size() > 0) { Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment. Role role = deployment.getRoleList().getRoles().get(0); String hostName = role.getRoleName(); // each deployment will have just one role. for (String prefix : prefixes) { if (hostName.contains(prefix)) { String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix); LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName); leakingAgentNodesPublicIps.add(publicIpFromDeployment); } } } } if (!leakingAgentNodesPublicIps.isEmpty()) { for (String ip : leakingAgentNodesPublicIps) { LogUtils.log("attempting to kill agent node : " + ip); long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME; try { azureClient.deleteVirtualMachineByIp(ip, false, endTime); } catch (final Exception e) { LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage()); } } return false; } else { return true; } } catch (final Exception e) { throw new RuntimeException(e); } }
diff --git a/src/fr/adrienbrault/idea/symfony2plugin/ServiceReferenceContributor.java b/src/fr/adrienbrault/idea/symfony2plugin/ServiceReferenceContributor.java index 6c0ae3c4..61b16c84 100644 --- a/src/fr/adrienbrault/idea/symfony2plugin/ServiceReferenceContributor.java +++ b/src/fr/adrienbrault/idea/symfony2plugin/ServiceReferenceContributor.java @@ -1,41 +1,41 @@ package fr.adrienbrault.idea.symfony2plugin; import com.intellij.patterns.PlatformPatterns; import com.intellij.psi.*; import com.intellij.util.ProcessingContext; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.MethodReference; import com.jetbrains.php.lang.psi.elements.ParameterList; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull; /** * @author Adrien Brault <[email protected]> */ public class ServiceReferenceContributor extends PsiReferenceContributor { @Override public void registerReferenceProviders(PsiReferenceRegistrar psiReferenceRegistrar) { psiReferenceRegistrar.registerReferenceProvider(PlatformPatterns.psiElement(StringLiteralExpression.class), new PsiReferenceProvider() { @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) { - ParameterList parameterList = (ParameterList) psiElement.getContext(); - if (!(parameterList instanceof ParameterList)) { + if (!(psiElement.getContext() instanceof ParameterList)) { return new PsiReference[0]; } + ParameterList parameterList = (ParameterList) psiElement.getContext(); - MethodReference method = (MethodReference) parameterList.getContext(); - if (!(method instanceof MethodReference)) { + if (!(parameterList.getContext() instanceof MethodReference)) { return new PsiReference[0]; } + MethodReference method = (MethodReference) parameterList.getContext(); if (!ContainerGetHelper.isContainerGetCall(method)) { return new PsiReference[0]; } return new PsiReference[]{ new ServiceReference((StringLiteralExpression) psiElement) }; } }); } }
false
true
public void registerReferenceProviders(PsiReferenceRegistrar psiReferenceRegistrar) { psiReferenceRegistrar.registerReferenceProvider(PlatformPatterns.psiElement(StringLiteralExpression.class), new PsiReferenceProvider() { @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) { ParameterList parameterList = (ParameterList) psiElement.getContext(); if (!(parameterList instanceof ParameterList)) { return new PsiReference[0]; } MethodReference method = (MethodReference) parameterList.getContext(); if (!(method instanceof MethodReference)) { return new PsiReference[0]; } if (!ContainerGetHelper.isContainerGetCall(method)) { return new PsiReference[0]; } return new PsiReference[]{ new ServiceReference((StringLiteralExpression) psiElement) }; } }); }
public void registerReferenceProviders(PsiReferenceRegistrar psiReferenceRegistrar) { psiReferenceRegistrar.registerReferenceProvider(PlatformPatterns.psiElement(StringLiteralExpression.class), new PsiReferenceProvider() { @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) { if (!(psiElement.getContext() instanceof ParameterList)) { return new PsiReference[0]; } ParameterList parameterList = (ParameterList) psiElement.getContext(); if (!(parameterList.getContext() instanceof MethodReference)) { return new PsiReference[0]; } MethodReference method = (MethodReference) parameterList.getContext(); if (!ContainerGetHelper.isContainerGetCall(method)) { return new PsiReference[0]; } return new PsiReference[]{ new ServiceReference((StringLiteralExpression) psiElement) }; } }); }
diff --git a/projects/connector-manager/source/java/com/google/enterprise/connector/traversal/QueryTraverser.java b/projects/connector-manager/source/java/com/google/enterprise/connector/traversal/QueryTraverser.java index 95d24fd2..12bd1d64 100644 --- a/projects/connector-manager/source/java/com/google/enterprise/connector/traversal/QueryTraverser.java +++ b/projects/connector-manager/source/java/com/google/enterprise/connector/traversal/QueryTraverser.java @@ -1,112 +1,112 @@ // Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.connector.traversal; import com.google.enterprise.connector.persist.ConnectorStateStore; import com.google.enterprise.connector.pusher.Pusher; import com.google.enterprise.connector.spi.PropertyMap; import com.google.enterprise.connector.spi.QueryTraversalManager; import com.google.enterprise.connector.spi.RepositoryException; import com.google.enterprise.connector.spi.ResultSet; import java.util.Iterator; /** * Traverser for a repository implemented using a QueryTraversalManager */ public class QueryTraverser implements Traverser { private Pusher pusher; private QueryTraversalManager queryTraversalManager; private ConnectorStateStore connectorStateStore; private String connectorName; public QueryTraverser(Pusher p, QueryTraversalManager q, ConnectorStateStore c, String n) { this.pusher = p; this.queryTraversalManager = q; this.connectorStateStore = c; this.connectorName = n; } /* * (non-Javadoc) * * @see com.google.enterprise.connector.traversal.Traverser#runBatch(int) */ - public int runBatch(int batchHint) throws InterruptedException { + public synchronized int runBatch(int batchHint) throws InterruptedException { int counter = 0; PropertyMap pm = null; String connectorState = connectorStateStore.getConnectorState(connectorName); ResultSet resultSet = null; if (connectorState == null) { try { resultSet = queryTraversalManager.startTraversal(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } else { try { resultSet = queryTraversalManager.resumeTraversal(connectorState); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } Iterator iter = null; try { iter = resultSet.iterator(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } while (iter.hasNext()) { if (Thread.currentThread().isInterrupted()) { checkpointAndSave(pm); throw new InterruptedException(); } pm = (PropertyMap) iter.next(); pusher.take(pm, connectorName); counter++; if (counter == batchHint) { break; } } if (counter != 0) { checkpointAndSave(pm); } return counter; } private void checkpointAndSave(PropertyMap pm) { String connectorState = null; try { connectorState = queryTraversalManager.checkpoint(pm); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } connectorStateStore.storeConnectorState(connectorName, connectorState); } }
true
true
public int runBatch(int batchHint) throws InterruptedException { int counter = 0; PropertyMap pm = null; String connectorState = connectorStateStore.getConnectorState(connectorName); ResultSet resultSet = null; if (connectorState == null) { try { resultSet = queryTraversalManager.startTraversal(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } else { try { resultSet = queryTraversalManager.resumeTraversal(connectorState); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } Iterator iter = null; try { iter = resultSet.iterator(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } while (iter.hasNext()) { if (Thread.currentThread().isInterrupted()) { checkpointAndSave(pm); throw new InterruptedException(); } pm = (PropertyMap) iter.next(); pusher.take(pm, connectorName); counter++; if (counter == batchHint) { break; } } if (counter != 0) { checkpointAndSave(pm); } return counter; }
public synchronized int runBatch(int batchHint) throws InterruptedException { int counter = 0; PropertyMap pm = null; String connectorState = connectorStateStore.getConnectorState(connectorName); ResultSet resultSet = null; if (connectorState == null) { try { resultSet = queryTraversalManager.startTraversal(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } else { try { resultSet = queryTraversalManager.resumeTraversal(connectorState); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } Iterator iter = null; try { iter = resultSet.iterator(); } catch (RepositoryException e) { // TODO:ziff Auto-generated catch block e.printStackTrace(); } while (iter.hasNext()) { if (Thread.currentThread().isInterrupted()) { checkpointAndSave(pm); throw new InterruptedException(); } pm = (PropertyMap) iter.next(); pusher.take(pm, connectorName); counter++; if (counter == batchHint) { break; } } if (counter != 0) { checkpointAndSave(pm); } return counter; }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index 07338e09..554bb4a2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -1,167 +1,167 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.InventoryWorkaround; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.Util; import java.util.Locale; import java.util.logging.Level; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandsell extends EssentialsCommand { public Commandsell() { super("sell"); } @Override public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } ItemStack is = null; if (args[0].equalsIgnoreCase("hand")) { is = user.getItemInHand(); } else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) { for (ItemStack stack : user.getInventory().getContents()) { if (stack == null || stack.getType() == Material.AIR) { continue; } try { sellItem(user, stack, args, true); } catch (Exception e) { } } return; } else if (args[0].equalsIgnoreCase("blocks")) { for (ItemStack stack : user.getInventory().getContents()) { if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) { continue; } try { sellItem(user, stack, args, true); } catch (Exception e) { } } return; } if (is == null) { is = ess.getItemDb().get(args[0]); } sellItem(user, is, args, false); } private void sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { if (is == null || is.getType() == Material.AIR) { throw new Exception(_("itemSellAir")); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); if (args[1].startsWith("-")) { amount = -amount; } } double worth = ess.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = ess.getSettings().isTradeInStacks(id); if (Double.isNaN(worth)) { throw new Exception(_("itemCannotBeSold")); } if (requireStack && !stack) { throw new Exception(_("itemMustBeStacked")); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } if (!s.getEnchantments().equals(is.getEnchantments())) { continue; } max += s.getAmount(); } if (stack) { amount *= is.getType().getMaxStackSize(); } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % is.getType().getMaxStackSize(); } if (amount > max || amount < 1) { if (!isBulkSell) { user.sendMessage(_("itemNotEnough1")); user.sendMessage(_("itemNotEnough2")); throw new Exception(_("itemNotEnough3")); } else { return; } } //TODO: Prices for Enchantments final ItemStack ris = is.clone(); - is.setAmount(amount); + ris.setAmount(amount); InventoryWorkaround.removeItem(user.getInventory(), true, ris); user.updateInventory(); Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess); user.giveMoney(worth * amount); user.sendMessage(_("itemSold", Util.formatCurrency(worth * amount, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth, ess))); logger.log(Level.INFO, _("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth * amount, ess), amount, Util.formatCurrency(worth, ess))); } }
true
true
private void sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { if (is == null || is.getType() == Material.AIR) { throw new Exception(_("itemSellAir")); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); if (args[1].startsWith("-")) { amount = -amount; } } double worth = ess.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = ess.getSettings().isTradeInStacks(id); if (Double.isNaN(worth)) { throw new Exception(_("itemCannotBeSold")); } if (requireStack && !stack) { throw new Exception(_("itemMustBeStacked")); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } if (!s.getEnchantments().equals(is.getEnchantments())) { continue; } max += s.getAmount(); } if (stack) { amount *= is.getType().getMaxStackSize(); } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % is.getType().getMaxStackSize(); } if (amount > max || amount < 1) { if (!isBulkSell) { user.sendMessage(_("itemNotEnough1")); user.sendMessage(_("itemNotEnough2")); throw new Exception(_("itemNotEnough3")); } else { return; } } //TODO: Prices for Enchantments final ItemStack ris = is.clone(); is.setAmount(amount); InventoryWorkaround.removeItem(user.getInventory(), true, ris); user.updateInventory(); Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess); user.giveMoney(worth * amount); user.sendMessage(_("itemSold", Util.formatCurrency(worth * amount, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth, ess))); logger.log(Level.INFO, _("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth * amount, ess), amount, Util.formatCurrency(worth, ess))); }
private void sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { if (is == null || is.getType() == Material.AIR) { throw new Exception(_("itemSellAir")); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); if (args[1].startsWith("-")) { amount = -amount; } } double worth = ess.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = ess.getSettings().isTradeInStacks(id); if (Double.isNaN(worth)) { throw new Exception(_("itemCannotBeSold")); } if (requireStack && !stack) { throw new Exception(_("itemMustBeStacked")); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } if (!s.getEnchantments().equals(is.getEnchantments())) { continue; } max += s.getAmount(); } if (stack) { amount *= is.getType().getMaxStackSize(); } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % is.getType().getMaxStackSize(); } if (amount > max || amount < 1) { if (!isBulkSell) { user.sendMessage(_("itemNotEnough1")); user.sendMessage(_("itemNotEnough2")); throw new Exception(_("itemNotEnough3")); } else { return; } } //TODO: Prices for Enchantments final ItemStack ris = is.clone(); ris.setAmount(amount); InventoryWorkaround.removeItem(user.getInventory(), true, ris); user.updateInventory(); Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess); user.giveMoney(worth * amount); user.sendMessage(_("itemSold", Util.formatCurrency(worth * amount, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth, ess))); logger.log(Level.INFO, _("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), Util.formatCurrency(worth * amount, ess), amount, Util.formatCurrency(worth, ess))); }
diff --git a/JavaSource/org/unitime/timetable/tags/Registration.java b/JavaSource/org/unitime/timetable/tags/Registration.java index 0f9ccb74..7871ba8f 100644 --- a/JavaSource/org/unitime/timetable/tags/Registration.java +++ b/JavaSource/org/unitime/timetable/tags/Registration.java @@ -1,205 +1,205 @@ /* * UniTime 3.2 (University Timetabling Application) * Copyright (C) 2010, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable.tags; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.restlet.resource.ClientResource; import org.unitime.commons.User; import org.unitime.commons.web.Web; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.model.QueryLog; import org.unitime.timetable.util.Constants; public class Registration extends BodyTagSupport { private static final long serialVersionUID = 6840487122075978529L; private static Log sLog = LogFactory.getLog(Registration.class); private static String sMessage = null; private static String sKey = null; private static boolean sRegistered = false; private static String sNote = null; private static enum Method { hasMessage, message, status }; private Method iMethod = Method.status; public String getMethod() { return iMethod.toString(); } public void setMethod(String method) { iMethod = Method.valueOf(method); } private boolean iUpdate = false; public void setUpdate(boolean update) { iUpdate = update; } public boolean isUpdate() { return iUpdate; } private static long sLastRefresh = -1; private synchronized void init() { sLastRefresh = System.currentTimeMillis(); try { File regFile = new File(ApplicationProperties.getDataFolder(), "unitime.reg"); if (sKey == null && regFile.exists()) { Properties reg = new Properties(); FileInputStream in = new FileInputStream(regFile); try { reg.load(in); } finally { in.close(); } sKey = reg.getProperty("key"); } HashMap<String, String> registration = new HashMap<String, String>(); if (sKey != null) registration.put("key", sKey); else sLog.debug("No registration key found..." ); registration.put("version", Constants.VERSION + "." + Constants.BLD_NUMBER.replace("@build.number@", "?")); registration.put("sessions", String.valueOf(QueryLog.getNrSessions(31))); registration.put("users", String.valueOf(QueryLog.getNrActiveUsers(31))); registration.put("url", pageContext.getRequest().getScheme()+"://"+pageContext.getRequest().getServerName()+":"+pageContext.getRequest().getServerPort()+ ((HttpServletRequest)pageContext.getRequest()).getContextPath()); sLog.debug("Sending the following registration info: " + registration); Document input = DocumentHelper.createDocument(); Element regEl = input.addElement("registration"); for (Map.Entry<String, String> entry: registration.entrySet()) { regEl.addElement(entry.getKey()).setText(entry.getValue()); } sLog.debug("Contacting registration service..." ); - ClientResource cr = new ClientResource("https://unitimereg.appspot.com/xml"); + ClientResource cr = new ClientResource("http://register.unitime.org/xml"); StringWriter w = new StringWriter(); new XMLWriter(w, OutputFormat.createPrettyPrint()).write(input); w.flush(); w.close(); String result = cr.post(w.toString(), String.class); sLog.debug("Registration information received." ); StringReader r = new StringReader(result); Document output = (new SAXReader()).read(r); r.close(); HashMap<String, String> ret = new HashMap<String, String>(); for (Element e: (List<Element>)output.getRootElement().elements()) { ret.put(e.getName(), e.getText()); } String newKey = ret.get("key"); if (!newKey.equals(sKey)) { sKey = newKey; sLog.debug("New registration key received..." ); Properties reg = new Properties(); reg.setProperty("key", sKey); FileOutputStream out = new FileOutputStream(regFile); try { reg.store(out, "UniTime 3.2 registration file, please do not delete or modify."); out.flush(); } finally { out.close(); } } sMessage = ret.get("message"); sNote = ret.get("note"); sRegistered = "1".equals(ret.get("registered")); } catch (Exception e) { sLog.error("Validation failed: " + e.getMessage(), e); } } private void refresh() { if ("1".equals(pageContext.getRequest().getParameter("refresh")) || System.currentTimeMillis() - sLastRefresh > 60 * 60 * 1000) init(); } public int doStartTag() throws JspException { if (sLastRefresh < 0) init(); switch (iMethod) { case hasMessage: User user = Web.getUser(pageContext.getSession()); if (user == null || !user.isAdmin()) return SKIP_BODY; try { refresh(); if (Registration.sNote != null && !Registration.sNote.isEmpty()) return EVAL_BODY_INCLUDE; } catch (Exception e) {} return SKIP_BODY; default: return EVAL_BODY_BUFFERED; } } public int doEndTag() throws JspException { switch (iMethod) { case hasMessage: return EVAL_PAGE; case message: try { User user = Web.getUser(pageContext.getSession()); if (Registration.sNote != null && user != null && user.isAdmin()) pageContext.getOut().println(Registration.sNote); } catch (Exception e) {} return EVAL_PAGE; case status: try { if (sMessage != null) { pageContext.getOut().println(sMessage); User user = Web.getUser(pageContext.getSession()); if (isUpdate() && user != null && user.isAdmin()) { String backUrl = URLEncoder.encode(((HttpServletRequest)pageContext.getRequest()).getRequestURL().toString() + "?refresh=1", "ISO-8859-1"); pageContext.getOut().println( "<br><span style=\"font-size: x-small;\">Click <a "+ "onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\" " + "onClick=\"showGwtDialog('UniTime 3.2 Registration', 'https://unitimereg.appspot.com?key=" + sKey + "&back=" + backUrl + "', '750px', '75%');\" " + "title='UniTime 3.2 Registration'>here</a> to " + (sRegistered ? "update the current registration" : "register") + "." + "</span>"); } } } catch (Exception e) {} return EVAL_PAGE; default: return EVAL_PAGE; } } }
true
true
private synchronized void init() { sLastRefresh = System.currentTimeMillis(); try { File regFile = new File(ApplicationProperties.getDataFolder(), "unitime.reg"); if (sKey == null && regFile.exists()) { Properties reg = new Properties(); FileInputStream in = new FileInputStream(regFile); try { reg.load(in); } finally { in.close(); } sKey = reg.getProperty("key"); } HashMap<String, String> registration = new HashMap<String, String>(); if (sKey != null) registration.put("key", sKey); else sLog.debug("No registration key found..." ); registration.put("version", Constants.VERSION + "." + Constants.BLD_NUMBER.replace("@build.number@", "?")); registration.put("sessions", String.valueOf(QueryLog.getNrSessions(31))); registration.put("users", String.valueOf(QueryLog.getNrActiveUsers(31))); registration.put("url", pageContext.getRequest().getScheme()+"://"+pageContext.getRequest().getServerName()+":"+pageContext.getRequest().getServerPort()+ ((HttpServletRequest)pageContext.getRequest()).getContextPath()); sLog.debug("Sending the following registration info: " + registration); Document input = DocumentHelper.createDocument(); Element regEl = input.addElement("registration"); for (Map.Entry<String, String> entry: registration.entrySet()) { regEl.addElement(entry.getKey()).setText(entry.getValue()); } sLog.debug("Contacting registration service..." ); ClientResource cr = new ClientResource("https://unitimereg.appspot.com/xml"); StringWriter w = new StringWriter(); new XMLWriter(w, OutputFormat.createPrettyPrint()).write(input); w.flush(); w.close(); String result = cr.post(w.toString(), String.class); sLog.debug("Registration information received." ); StringReader r = new StringReader(result); Document output = (new SAXReader()).read(r); r.close(); HashMap<String, String> ret = new HashMap<String, String>(); for (Element e: (List<Element>)output.getRootElement().elements()) { ret.put(e.getName(), e.getText()); } String newKey = ret.get("key"); if (!newKey.equals(sKey)) { sKey = newKey; sLog.debug("New registration key received..." ); Properties reg = new Properties(); reg.setProperty("key", sKey); FileOutputStream out = new FileOutputStream(regFile); try { reg.store(out, "UniTime 3.2 registration file, please do not delete or modify."); out.flush(); } finally { out.close(); } } sMessage = ret.get("message"); sNote = ret.get("note"); sRegistered = "1".equals(ret.get("registered")); } catch (Exception e) { sLog.error("Validation failed: " + e.getMessage(), e); } }
private synchronized void init() { sLastRefresh = System.currentTimeMillis(); try { File regFile = new File(ApplicationProperties.getDataFolder(), "unitime.reg"); if (sKey == null && regFile.exists()) { Properties reg = new Properties(); FileInputStream in = new FileInputStream(regFile); try { reg.load(in); } finally { in.close(); } sKey = reg.getProperty("key"); } HashMap<String, String> registration = new HashMap<String, String>(); if (sKey != null) registration.put("key", sKey); else sLog.debug("No registration key found..." ); registration.put("version", Constants.VERSION + "." + Constants.BLD_NUMBER.replace("@build.number@", "?")); registration.put("sessions", String.valueOf(QueryLog.getNrSessions(31))); registration.put("users", String.valueOf(QueryLog.getNrActiveUsers(31))); registration.put("url", pageContext.getRequest().getScheme()+"://"+pageContext.getRequest().getServerName()+":"+pageContext.getRequest().getServerPort()+ ((HttpServletRequest)pageContext.getRequest()).getContextPath()); sLog.debug("Sending the following registration info: " + registration); Document input = DocumentHelper.createDocument(); Element regEl = input.addElement("registration"); for (Map.Entry<String, String> entry: registration.entrySet()) { regEl.addElement(entry.getKey()).setText(entry.getValue()); } sLog.debug("Contacting registration service..." ); ClientResource cr = new ClientResource("http://register.unitime.org/xml"); StringWriter w = new StringWriter(); new XMLWriter(w, OutputFormat.createPrettyPrint()).write(input); w.flush(); w.close(); String result = cr.post(w.toString(), String.class); sLog.debug("Registration information received." ); StringReader r = new StringReader(result); Document output = (new SAXReader()).read(r); r.close(); HashMap<String, String> ret = new HashMap<String, String>(); for (Element e: (List<Element>)output.getRootElement().elements()) { ret.put(e.getName(), e.getText()); } String newKey = ret.get("key"); if (!newKey.equals(sKey)) { sKey = newKey; sLog.debug("New registration key received..." ); Properties reg = new Properties(); reg.setProperty("key", sKey); FileOutputStream out = new FileOutputStream(regFile); try { reg.store(out, "UniTime 3.2 registration file, please do not delete or modify."); out.flush(); } finally { out.close(); } } sMessage = ret.get("message"); sNote = ret.get("note"); sRegistered = "1".equals(ret.get("registered")); } catch (Exception e) { sLog.error("Validation failed: " + e.getMessage(), e); } }
diff --git a/richfaces/src/main/java/be/cegeka/rsvz/LocaleBean.java b/richfaces/src/main/java/be/cegeka/rsvz/LocaleBean.java index a4a9c37..96920b7 100644 --- a/richfaces/src/main/java/be/cegeka/rsvz/LocaleBean.java +++ b/richfaces/src/main/java/be/cegeka/rsvz/LocaleBean.java @@ -1,99 +1,98 @@ package be.cegeka.rsvz; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; @ManagedBean @SessionScoped public class LocaleBean implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(LocaleBean.class); private Locale locale; private List<Locale> locales; public LocaleBean() { this.locales = extractLocales(); this.locale = extractBrowserLocale(); LOG.info("Locale set to {}", locale); LOG.info("Available locales: {}", locales); } public Locale getLocale() { return locale; } public String getLanguage() { return locale.toString(); } public List<SelectItem> getLanguages() { List<SelectItem> languages = new ArrayList<SelectItem>(); for (Locale locale : locales) { languages.add(localeToSelectItem(locale)); } return languages; } public void setLanguage(String language) { locale = extractLocale(language); FacesContext.getCurrentInstance().getViewRoot().setLocale(locale); } private Locale extractBrowserLocale() { Locale locale = ((HttpServletRequest) (FacesContext.getCurrentInstance(). getExternalContext().getRequest())).getLocale(); if (locales.contains(locale)) { return locale; } else { return getDefaultLocale(); } } private Locale getDefaultLocale() { return FacesContext.getCurrentInstance().getApplication().getDefaultLocale(); } private Locale extractLocale(String localeCode) { - LOG.debug("Parsing {}", localeCode); String language = localeCode.substring(0, 2); String country; if (localeCode.length() > 2) { country = localeCode.substring(3, 5); } else { country = ""; } LOG.info("Setting locale to language={} country={}", language, country); return new Locale(language, country); } private List<Locale> extractLocales() { List<Locale> locales = new ArrayList<Locale>(); locales.add(getDefaultLocale()); Iterator<Locale> i = FacesContext.getCurrentInstance().getApplication().getSupportedLocales(); while (i.hasNext()) { locales.add(i.next()); } return locales; } private SelectItem localeToSelectItem(Locale locale) { if (locale != null) { return new SelectItem(locale.toString(), locale.getDisplayName()); } return null; } }
true
true
private Locale extractLocale(String localeCode) { LOG.debug("Parsing {}", localeCode); String language = localeCode.substring(0, 2); String country; if (localeCode.length() > 2) { country = localeCode.substring(3, 5); } else { country = ""; } LOG.info("Setting locale to language={} country={}", language, country); return new Locale(language, country); }
private Locale extractLocale(String localeCode) { String language = localeCode.substring(0, 2); String country; if (localeCode.length() > 2) { country = localeCode.substring(3, 5); } else { country = ""; } LOG.info("Setting locale to language={} country={}", language, country); return new Locale(language, country); }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISCommands.java b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISCommands.java index a404f8809..711047800 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISCommands.java +++ b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISCommands.java @@ -1,1258 +1,1258 @@ /* * Copyright (C) 2012 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.commands; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import me.eccentric_nz.TARDIS.TARDISConstants.ROOM; import me.eccentric_nz.TARDIS.database.QueryFactory; import me.eccentric_nz.TARDIS.database.ResultSetDestinations; import me.eccentric_nz.TARDIS.database.ResultSetTardis; import me.eccentric_nz.TARDIS.database.ResultSetTravellers; import me.eccentric_nz.TARDIS.database.TARDISDatabase; import me.eccentric_nz.TARDIS.files.TARDISUpdateChecker; import me.eccentric_nz.TARDIS.thirdparty.Version; import me.eccentric_nz.TARDIS.travel.TARDISPluginRespect; import me.eccentric_nz.TARDIS.travel.TARDISTimetravel; import me.eccentric_nz.TARDIS.utility.TARDISItemRenamer; import me.eccentric_nz.TARDIS.utility.TARDISLister; import me.eccentric_nz.tardischunkgenerator.TARDISChunkGenerator; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.inventory.ItemStack; import org.getspout.spoutapi.SpoutManager; /** * A TARDIS console room or control room is the area which houses the TARDIS' * control console, by which the TARDIS was operated. * * @author eccentric_nz */ public class TARDISCommands implements CommandExecutor { private TARDIS plugin; private TARDISPluginRespect respect; HashSet<Byte> transparent = new HashSet<Byte>(); private List<String> firstArgs = new ArrayList<String>(); private List<String> roomArgs = new ArrayList<String>(); Version bukkitversion; Version preIMversion = new Version("1.4.5"); Version SUBversion; Version preSUBversion = new Version("1.0"); public TARDISCommands(TARDIS plugin) { this.plugin = plugin; // add transparent blocks transparent.add((byte) Material.AIR.getId()); transparent.add((byte) Material.SNOW.getId()); transparent.add((byte) Material.LONG_GRASS.getId()); transparent.add((byte) Material.VINE.getId()); transparent.add((byte) Material.DEAD_BUSH.getId()); // add first arguments firstArgs.add("chameleon"); firstArgs.add("save"); firstArgs.add("removesave"); firstArgs.add("list"); firstArgs.add("help"); firstArgs.add("find"); firstArgs.add("reload"); firstArgs.add("add"); firstArgs.add("remove"); firstArgs.add("update"); firstArgs.add("rebuild"); firstArgs.add("comehere"); firstArgs.add("occupy"); firstArgs.add("direction"); firstArgs.add("setdest"); firstArgs.add("hide"); firstArgs.add("home"); firstArgs.add("namekey"); firstArgs.add("version"); firstArgs.add("room"); firstArgs.add("jettison"); firstArgs.add("bind"); firstArgs.add("unbind"); firstArgs.add("check_loc"); firstArgs.add("gravity"); // rooms for (ROOM r : ROOM.values()) { roomArgs.add(r.toString()); } String[] v = Bukkit.getServer().getBukkitVersion().split("-"); bukkitversion = new Version(v[0]); SUBversion = new Version(v[1].substring(1, v[1].length())); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardis then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } // the command list - first argument MUST appear here! if (!firstArgs.contains(args[0].toLowerCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That command wasn't recognised type " + ChatColor.GREEN + "/tardis help" + ChatColor.RESET + " to see the commands"); return false; } // temporary command to convert old gravity well to new style if (args[0].equalsIgnoreCase("gravity")) { if (player == null) { sender.sendMessage(plugin.pluginName + "Must be a player"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); try { TARDISDatabase service = TARDISDatabase.getInstance(); Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM gravity WHERE tardis_id = " + id; ResultSet rsg = statement.executeQuery(query); if (rsg.isBeforeFirst()) { // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14,y=10.0,z=27,pitch=0.0,yaw=0.0} // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14.0,y=10.0,z=5.0,pitch=0.0,yaw=0.0} String up = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("upx") + ",y=10.0,z=" + rsg.getFloat("upz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityUpList.add(up); String down = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("downx") + ",y=10.0,z=" + rsg.getFloat("downz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityDownList.add(down); HashMap<String, Object> setu = new HashMap<String, Object>(); setu.put("tardis_id", id); setu.put("location", up); setu.put("direction", 1); HashMap<String, Object> setd = new HashMap<String, Object>(); setd.put("tardis_id", id); setd.put("location", down); setd.put("direction", 0); QueryFactory qf = new QueryFactory(plugin); qf.doInsert("gravity_well", setu); qf.doInsert("gravity_well", setd); player.sendMessage(plugin.pluginName + "Gravity well converted successfully."); return true; } } catch (SQLException e) { plugin.debug("Gravity conversion error: " + e.getMessage()); } } if (args[0].equalsIgnoreCase("version")) { FileConfiguration pluginYml = YamlConfiguration.loadConfiguration(plugin.pm.getPlugin("TARDIS").getResource("plugin.yml")); String version = pluginYml.getString("version"); String cb = Bukkit.getVersion(); sender.sendMessage(plugin.pluginName + "You are running TARDIS version: " + ChatColor.AQUA + version + ChatColor.RESET + " with CraftBukkit " + cb); // also check if there is an update if (plugin.getConfig().getBoolean("check_for_updates")) { TARDISUpdateChecker update = new TARDISUpdateChecker(plugin); update.checkVersion(player); } return true; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("chameleon")) { if (!plugin.getConfig().getBoolean("chameleon")) { sender.sendMessage(plugin.pluginName + "This server does not allow the use of the chameleon circuit!"); return false; } if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("on") && !args[1].equalsIgnoreCase("off"))) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String chamStr = rs.getChameleon(); if (chamStr.equals("")) { sender.sendMessage(plugin.pluginName + "Could not find the Chameleon Circuit!"); return false; } else { int x, y, z; String[] chamData = chamStr.split(":"); World w = plugin.getServer().getWorld(chamData[0]); TARDISConstants.COMPASS d = rs.getDirection(); x = plugin.utils.parseNum(chamData[1]); y = plugin.utils.parseNum(chamData[2]); z = plugin.utils.parseNum(chamData[3]); Block chamBlock = w.getBlockAt(x, y, z); Material chamType = chamBlock.getType(); if (chamType == Material.WALL_SIGN || chamType == Material.SIGN_POST) { Sign cs = (Sign) chamBlock.getState(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (args[1].equalsIgnoreCase("on")) { set.put("chamele_on", 1); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned ON!"); cs.setLine(3, ChatColor.GREEN + "ON"); } if (args[1].equalsIgnoreCase("off")) { set.put("chamele_on", 0); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned OFF."); cs.setLine(3, ChatColor.RED + "OFF"); } cs.update(); } } return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("room")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: passage|arboretum|pool|vault|kitchen|bedroom|library|workshop|empty|gravity"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } String chunk = rs.getChunk(); String[] data = chunk.split(":"); World room_world = plugin.getServer().getWorld(data[0]); ChunkGenerator gen = room_world.getGenerator(); WorldType wt = room_world.getWorldType(); boolean special = (data[0].contains("TARDIS_TimeVortex") && (wt.equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator)); if (!data[0].contains("TARDIS_WORLD_") && !special) { player.sendMessage(plugin.pluginName + "You cannot grow rooms unless your TARDIS was created in its own world!"); return true; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } // check they have enough artron energy if (level < plugin.getConfig().getInt("rooms." + room + ".cost")) { player.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to grow this room!"); return true; } String message; // if it is a gravity well if (room.equals("GRAVITY")) { message = "Place the GRAVITY WELL seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") into the centre of the floor in an empty room, then hit it with the TARDIS key to start growing your room!"; } else { message = "Place the " + room + " seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") where the door should be, then hit it with the TARDIS key to start growing your room!"; } plugin.trackRoomSeed.put(player.getName(), room); player.sendMessage(plugin.pluginName + message); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("jettison")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (room.equals("GRAVITY")) { player.sendMessage(plugin.pluginName + "You cannot jettison gravity wells!"); return true; } - if (!Arrays.asList(ROOM.values()).contains(ROOM.valueOf(room))) { + if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of : passage|arboretum|pool|vault|kitchen|bedroom|library|empty"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } int id = rs.getTardis_id(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } plugin.trackJettison.put(player.getName(), room); player.sendMessage(plugin.pluginName + "Stand in the doorway of the room you want to jettison and place a TNT block directly in front of the door. Hit the TNT with the TARDIS key to jettison the room!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("occupy")) { if (player.hasPermission("tardis.timetravel")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + " You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); String occupied; QueryFactory qf = new QueryFactory(plugin); if (rst.resultSet()) { HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("player", player.getName()); qf.doDelete("travellers", whered); occupied = ChatColor.RED + "UNOCCUPIED"; } else { HashMap<String, Object> wherei = new HashMap<String, Object>(); wherei.put("tardis_id", id); wherei.put("player", player.getName()); qf.doInsert("travellers", wherei); occupied = ChatColor.GREEN + "OCCUPIED"; } sender.sendMessage(plugin.pluginName + " TARDIS occupation was set to: " + occupied); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("comehere")) { if (player.hasPermission("tardis.timetravel")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to bring the TARDIS to this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return false; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, eyeLocation)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to bring the TARDIS to this location!"); return false; } } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); final ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return true; } final int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); int[] start_loc = tt.getStartLocation(eyeLocation, d); // safeLocation(int startx, int starty, int startz, int resetx, int resetz, World w, TARDISConstants.COMPASS d) int count = tt.safeLocation(start_loc[0], eyeLocation.getBlockY(), start_loc[2], start_loc[1], start_loc[3], eyeLocation.getWorld(), d); if (count > 0) { sender.sendMessage(plugin.pluginName + "That location would grief existing blocks! Try somewhere else!"); return true; } int level = rs.getArtron_level(); int ch = plugin.getConfig().getInt("comehere"); if (level < ch) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!"); return true; } final Player p = player; String badsave = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); boolean chamtmp = false; if (plugin.getConfig().getBoolean("chameleon")) { chamtmp = rs.isChamele_on(); } final boolean cham = chamtmp; String[] saveData = badsave.split(":"); World w = plugin.getServer().getWorld(saveData[0]); int x, y, z; x = plugin.utils.parseNum(saveData[1]); y = plugin.utils.parseNum(saveData[2]); z = plugin.utils.parseNum(saveData[3]); final Location oldSave = w.getBlockAt(x, y, z).getLocation(); //rs.close(); String comehere = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", comehere); set.put("current", comehere); qf.doUpdate("tardis", set, tid); // how many travellers are in the TARDIS? plugin.utils.updateTravellerCount(id); sender.sendMessage(plugin.pluginName + "The TARDIS is coming..."); long delay = 100L; if (plugin.getServer().getPluginManager().getPlugin("Spout") != null && SpoutManager.getPlayer(player).isSpoutCraftEnabled()) { SpoutManager.getSoundManager().playCustomSoundEffect(plugin, SpoutManager.getPlayer(player), "https://dl.dropbox.com/u/53758864/tardis_land.mp3", false, eyeLocation, 9, 75); delay = 400L; } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(oldSave, d); plugin.destroyPB.destroyTorch(oldSave); plugin.destroyPB.destroyPoliceBox(oldSave, d, id, false); plugin.buildPB.buildPoliceBox(id, eyeLocation, d, cham, p, false); } }, delay); // remove energy from TARDIS HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); qf.alterEnergyLevel("tardis", -ch, wheret, player); plugin.tardisHasDestination.remove(id); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("check_loc")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); tt.testSafeLocation(eyeLocation, d); return true; } if (args[0].equalsIgnoreCase("home")) { if (player.hasPermission("tardis.timetravel")) { Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS home in this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot set the TARDIS home location to this world"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot set the home locatopn here because you are inside a TARDIS!"); return true; } String sethome = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("home", sethome); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The new TARDIS home was set!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"door", "button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "chameleon", "save-sign", "artron", "handbrake", "condenser"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!Arrays.asList(validBlockNames).contains(args[1].toLowerCase(Locale.ENGLISH))) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : door|button|world-repeater|x-repeater|z-repeater|y-repeater|chameleon|save-sign|artron|handbrake|condenser"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } plugin.trackPlayers.put(player.getName(), args[1].toLowerCase(Locale.ENGLISH)); player.sendMessage(plugin.pluginName + "Click the TARDIS " + args[1].toLowerCase(Locale.ENGLISH) + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("bind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } int did; HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1]); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); QueryFactory qf = new QueryFactory(plugin); did = qf.doInsert("destinations", set); } else { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } } else { did = rsd.getDest_id(); } plugin.trackBinder.put(player.getName(), did); player.sendMessage(plugin.pluginName + "Click the block you want to bind to this save location."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("unbind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } if (rsd.getBind().equals("")) { sender.sendMessage(plugin.pluginName + "There is no button bound to that save name!"); return true; } int did = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("dest_id", did); if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { // delete the record qf.doDelete("destinations", whereb); } else { // just remove the bind location HashMap<String, Object> set = new HashMap<String, Object>(); set.put("bind", ""); qf.doUpdate("destinations", set, whereb); } player.sendMessage(plugin.pluginName + "The location was unbound. You can safely delete the block."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rebuild") || args[0].equalsIgnoreCase("hide")) { if (player.hasPermission("tardis.rebuild")) { String save; World w; int x, y, z, id; TARDISConstants.COMPASS d; boolean cham = false; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } id = rs.getTardis_id(); save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } d = rs.getDirection(); String[] save_data = save.split(":"); w = plugin.getServer().getWorld(save_data[0]); x = plugin.utils.parseNum(save_data[1]); y = plugin.utils.parseNum(save_data[2]); z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); if (args[0].equalsIgnoreCase("rebuild")) { plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was rebuilt!"); return true; } if (args[0].equalsIgnoreCase("hide")) { int level = rs.getArtron_level(); int hide = plugin.getConfig().getInt("hide"); if (level < hide) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to hide!"); return false; } // remove torch plugin.destroyPB.destroyTorch(l); // remove sign plugin.destroyPB.destroySign(l, d); // remove blue box plugin.destroyPB.destroyPoliceBox(l, d, id, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was hidden! Use " + ChatColor.GREEN + "/tardis rebuild" + ChatColor.RESET + " to show it again."); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); QueryFactory qf = new QueryFactory(plugin); qf.alterEnergyLevel("tardis", -hide, wheret, player); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("tardis.list")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2 || (!args[1].equalsIgnoreCase("saves") && !args[1].equalsIgnoreCase("companions") && !args[1].equalsIgnoreCase("areas") && !args[1].equalsIgnoreCase("rechargers"))) { sender.sendMessage(plugin.pluginName + "You need to specify which TARDIS list you want to view! [saves|companions|areas|rechargers]"); return false; } TARDISLister.list(player, args[1]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (player.hasPermission("tardis.find")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String loc = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] findData = loc.split(":"); sender.sendMessage(plugin.pluginName + "TARDIS was left at " + findData[0] + " at x: " + findData[1] + " y: " + findData[2] + " z: " + findData[3]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (comps != null && !comps.equals("")) { // add to the list String newList = comps + ":" + args[1].toLowerCase(Locale.ENGLISH); set.put("companions", newList); } else { // make a list set.put("companions", args[1].toLowerCase(Locale.ENGLISH)); } qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); if (comps == null || comps.equals("")) { sender.sendMessage(plugin.pluginName + "You have not added any TARDIS companions yet!"); return true; } } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { String[] split = comps.split(":"); StringBuilder buf = new StringBuilder(); String newList; if (split.length > 1) { // recompile string without the specified player for (String c : split) { if (!c.equals(args[1].toLowerCase(Locale.ENGLISH))) { // add to new string buf.append(c).append(":"); } } // remove trailing colon newList = buf.toString().substring(0, buf.length() - 1); } else { newList = ""; } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("companions", newList); qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid save name (it may be too long or contains spaces)."); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { String cur = rs.getCurrent(); String sav = rs.getSave(); int id = rs.getTardis_id(); String[] curDest; // get current destination HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (rst.resultSet() || plugin.tardisHasDestination.containsKey(id)) { // inside TARDIS curDest = cur.split(":"); } else { // outside TARDIS curDest = sav.split(":"); } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", curDest[0]); set.put("x", plugin.utils.parseNum(curDest[1])); set.put("y", plugin.utils.parseNum(curDest[2])); set.put("z", plugin.utils.parseNum(curDest[3])); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The location '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("removesave")) { if (player.hasPermission("tardis.save")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("dest_name", args[1]); whered.put("tardis_id", id); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a saved destination with that name!"); return false; } int destID = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> did = new HashMap<String, Object>(); did.put("dest_id", destID); qf.doDelete("destinations", did); sender.sendMessage(plugin.pluginName + "The destination " + args[1] + " was deleted!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("setdest")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "The destination name must be between 2 and 16 characters and have no spaces!"); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } // get location player is looking at Block b = player.getTargetBlock(transparent, 50); Location l = b.getLocation(); String world = l.getWorld().getName(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && world.equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS destination to this world!"); return true; } // check the world is not excluded if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, l, true)) { return true; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, l)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to save the TARDIS to this location!"); return false; } } String dw = l.getWorld().getName(); int dx = l.getBlockX(); int dy = l.getBlockY() + 1; int dz = l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", dw); set.put("x", dx); set.put("y", dy); set.put("z", dz); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The destination '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("direction")) { if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("north") && !args[1].equalsIgnoreCase("west") && !args[1].equalsIgnoreCase("south") && !args[1].equalsIgnoreCase("east"))) { sender.sendMessage(plugin.pluginName + "You need to specify the compass direction e.g. north, west, south or east!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] save_data = save.split(":"); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } boolean cham = false; if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } String dir = args[1].toUpperCase(Locale.ENGLISH); TARDISConstants.COMPASS old_d = rs.getDirection(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("direction", dir); qf.doUpdate("tardis", set, tid); HashMap<String, Object> did = new HashMap<String, Object>(); HashMap<String, Object> setd = new HashMap<String, Object>(); did.put("door_type", 0); did.put("tardis_id", id); setd.put("door_direction", dir); qf.doUpdate("doors", setd, did); World w = plugin.getServer().getWorld(save_data[0]); int x = plugin.utils.parseNum(save_data[1]); int y = plugin.utils.parseNum(save_data[2]); int z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(dir); // destroy platform plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(l, old_d); plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("namekey")) { if (bukkitversion.compareTo(preIMversion) < 0 || (bukkitversion.compareTo(preIMversion) == 0 && SUBversion.compareTo(preSUBversion) < 0)) { sender.sendMessage(plugin.pluginName + "You cannot rename the TARDIS key with this version of Bukkit!"); return true; } Material m = Material.getMaterial(plugin.getConfig().getString("key")); ItemStack is = player.getItemInHand(); if (!is.getType().equals(m)) { sender.sendMessage(plugin.pluginName + "You can only rename the TARDIS key!"); return true; } int count = args.length; if (count < 2) { return false; } StringBuilder buf = new StringBuilder(args[1]); for (int i = 2; i < count; i++) { buf.append(" ").append(args[i]); } String tmp = buf.toString(); TARDISItemRenamer ir = new TARDISItemRenamer(is); ir.setName(tmp, false); sender.sendMessage(plugin.pluginName + "TARDIS key renamed to '" + tmp + "'"); return true; } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } if (args.length == 2) { List<String> cmds = new ArrayList<String>(); for (TARDISConstants.CMDS c : TARDISConstants.CMDS.values()) { cmds.add(c.toString()); } // check that the second arument is valid if (!cmds.contains(args[1].toUpperCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That is not a valid help topic!"); return true; } switch (TARDISConstants.fromString(args[1])) { case CREATE: sender.sendMessage(TARDISConstants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(TARDISConstants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(TARDISConstants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(TARDISConstants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(TARDISConstants.COMMAND_SAVE.split("\n")); break; case REMOVESAVE: sender.sendMessage(TARDISConstants.COMMAND_REMOVESAVE.split("\n")); break; case ADD: sender.sendMessage(TARDISConstants.COMMAND_ADD.split("\n")); break; case TRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TRAVEL.split("\n")); break; case UPDATE: sender.sendMessage(TARDISConstants.COMMAND_UPDATE.split("\n")); break; case REBUILD: sender.sendMessage(TARDISConstants.COMMAND_REBUILD.split("\n")); break; case CHAMELEON: sender.sendMessage(TARDISConstants.COMMAND_CHAMELEON.split("\n")); break; case SFX: sender.sendMessage(TARDISConstants.COMMAND_SFX.split("\n")); break; case PLATFORM: sender.sendMessage(TARDISConstants.COMMAND_PLATFORM.split("\n")); break; case SETDEST: sender.sendMessage(TARDISConstants.COMMAND_SETDEST.split("\n")); break; case HOME: sender.sendMessage(TARDISConstants.COMMAND_HOME.split("\n")); break; case HIDE: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case VERSION: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case ADMIN: sender.sendMessage(TARDISConstants.COMMAND_ADMIN.split("\n")); break; case AREA: sender.sendMessage(TARDISConstants.COMMAND_AREA.split("\n")); break; case ROOM: sender.sendMessage(TARDISConstants.COMMAND_ROOM.split("\n")); break; case ARTRON: sender.sendMessage(TARDISConstants.COMMAND_ARTRON.split("\n")); break; case BIND: sender.sendMessage(TARDISConstants.COMMAND_BIND.split("\n")); break; default: sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); } } return true; } } } // If the above has happened the function will break and return true. if this hasn't happened then value of false will be returned. return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardis then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } // the command list - first argument MUST appear here! if (!firstArgs.contains(args[0].toLowerCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That command wasn't recognised type " + ChatColor.GREEN + "/tardis help" + ChatColor.RESET + " to see the commands"); return false; } // temporary command to convert old gravity well to new style if (args[0].equalsIgnoreCase("gravity")) { if (player == null) { sender.sendMessage(plugin.pluginName + "Must be a player"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); try { TARDISDatabase service = TARDISDatabase.getInstance(); Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM gravity WHERE tardis_id = " + id; ResultSet rsg = statement.executeQuery(query); if (rsg.isBeforeFirst()) { // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14,y=10.0,z=27,pitch=0.0,yaw=0.0} // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14.0,y=10.0,z=5.0,pitch=0.0,yaw=0.0} String up = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("upx") + ",y=10.0,z=" + rsg.getFloat("upz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityUpList.add(up); String down = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("downx") + ",y=10.0,z=" + rsg.getFloat("downz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityDownList.add(down); HashMap<String, Object> setu = new HashMap<String, Object>(); setu.put("tardis_id", id); setu.put("location", up); setu.put("direction", 1); HashMap<String, Object> setd = new HashMap<String, Object>(); setd.put("tardis_id", id); setd.put("location", down); setd.put("direction", 0); QueryFactory qf = new QueryFactory(plugin); qf.doInsert("gravity_well", setu); qf.doInsert("gravity_well", setd); player.sendMessage(plugin.pluginName + "Gravity well converted successfully."); return true; } } catch (SQLException e) { plugin.debug("Gravity conversion error: " + e.getMessage()); } } if (args[0].equalsIgnoreCase("version")) { FileConfiguration pluginYml = YamlConfiguration.loadConfiguration(plugin.pm.getPlugin("TARDIS").getResource("plugin.yml")); String version = pluginYml.getString("version"); String cb = Bukkit.getVersion(); sender.sendMessage(plugin.pluginName + "You are running TARDIS version: " + ChatColor.AQUA + version + ChatColor.RESET + " with CraftBukkit " + cb); // also check if there is an update if (plugin.getConfig().getBoolean("check_for_updates")) { TARDISUpdateChecker update = new TARDISUpdateChecker(plugin); update.checkVersion(player); } return true; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("chameleon")) { if (!plugin.getConfig().getBoolean("chameleon")) { sender.sendMessage(plugin.pluginName + "This server does not allow the use of the chameleon circuit!"); return false; } if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("on") && !args[1].equalsIgnoreCase("off"))) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String chamStr = rs.getChameleon(); if (chamStr.equals("")) { sender.sendMessage(plugin.pluginName + "Could not find the Chameleon Circuit!"); return false; } else { int x, y, z; String[] chamData = chamStr.split(":"); World w = plugin.getServer().getWorld(chamData[0]); TARDISConstants.COMPASS d = rs.getDirection(); x = plugin.utils.parseNum(chamData[1]); y = plugin.utils.parseNum(chamData[2]); z = plugin.utils.parseNum(chamData[3]); Block chamBlock = w.getBlockAt(x, y, z); Material chamType = chamBlock.getType(); if (chamType == Material.WALL_SIGN || chamType == Material.SIGN_POST) { Sign cs = (Sign) chamBlock.getState(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (args[1].equalsIgnoreCase("on")) { set.put("chamele_on", 1); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned ON!"); cs.setLine(3, ChatColor.GREEN + "ON"); } if (args[1].equalsIgnoreCase("off")) { set.put("chamele_on", 0); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned OFF."); cs.setLine(3, ChatColor.RED + "OFF"); } cs.update(); } } return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("room")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: passage|arboretum|pool|vault|kitchen|bedroom|library|workshop|empty|gravity"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } String chunk = rs.getChunk(); String[] data = chunk.split(":"); World room_world = plugin.getServer().getWorld(data[0]); ChunkGenerator gen = room_world.getGenerator(); WorldType wt = room_world.getWorldType(); boolean special = (data[0].contains("TARDIS_TimeVortex") && (wt.equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator)); if (!data[0].contains("TARDIS_WORLD_") && !special) { player.sendMessage(plugin.pluginName + "You cannot grow rooms unless your TARDIS was created in its own world!"); return true; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } // check they have enough artron energy if (level < plugin.getConfig().getInt("rooms." + room + ".cost")) { player.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to grow this room!"); return true; } String message; // if it is a gravity well if (room.equals("GRAVITY")) { message = "Place the GRAVITY WELL seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") into the centre of the floor in an empty room, then hit it with the TARDIS key to start growing your room!"; } else { message = "Place the " + room + " seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") where the door should be, then hit it with the TARDIS key to start growing your room!"; } plugin.trackRoomSeed.put(player.getName(), room); player.sendMessage(plugin.pluginName + message); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("jettison")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (room.equals("GRAVITY")) { player.sendMessage(plugin.pluginName + "You cannot jettison gravity wells!"); return true; } if (!Arrays.asList(ROOM.values()).contains(ROOM.valueOf(room))) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of : passage|arboretum|pool|vault|kitchen|bedroom|library|empty"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } int id = rs.getTardis_id(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } plugin.trackJettison.put(player.getName(), room); player.sendMessage(plugin.pluginName + "Stand in the doorway of the room you want to jettison and place a TNT block directly in front of the door. Hit the TNT with the TARDIS key to jettison the room!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("occupy")) { if (player.hasPermission("tardis.timetravel")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + " You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); String occupied; QueryFactory qf = new QueryFactory(plugin); if (rst.resultSet()) { HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("player", player.getName()); qf.doDelete("travellers", whered); occupied = ChatColor.RED + "UNOCCUPIED"; } else { HashMap<String, Object> wherei = new HashMap<String, Object>(); wherei.put("tardis_id", id); wherei.put("player", player.getName()); qf.doInsert("travellers", wherei); occupied = ChatColor.GREEN + "OCCUPIED"; } sender.sendMessage(plugin.pluginName + " TARDIS occupation was set to: " + occupied); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("comehere")) { if (player.hasPermission("tardis.timetravel")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to bring the TARDIS to this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return false; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, eyeLocation)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to bring the TARDIS to this location!"); return false; } } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); final ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return true; } final int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); int[] start_loc = tt.getStartLocation(eyeLocation, d); // safeLocation(int startx, int starty, int startz, int resetx, int resetz, World w, TARDISConstants.COMPASS d) int count = tt.safeLocation(start_loc[0], eyeLocation.getBlockY(), start_loc[2], start_loc[1], start_loc[3], eyeLocation.getWorld(), d); if (count > 0) { sender.sendMessage(plugin.pluginName + "That location would grief existing blocks! Try somewhere else!"); return true; } int level = rs.getArtron_level(); int ch = plugin.getConfig().getInt("comehere"); if (level < ch) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!"); return true; } final Player p = player; String badsave = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); boolean chamtmp = false; if (plugin.getConfig().getBoolean("chameleon")) { chamtmp = rs.isChamele_on(); } final boolean cham = chamtmp; String[] saveData = badsave.split(":"); World w = plugin.getServer().getWorld(saveData[0]); int x, y, z; x = plugin.utils.parseNum(saveData[1]); y = plugin.utils.parseNum(saveData[2]); z = plugin.utils.parseNum(saveData[3]); final Location oldSave = w.getBlockAt(x, y, z).getLocation(); //rs.close(); String comehere = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", comehere); set.put("current", comehere); qf.doUpdate("tardis", set, tid); // how many travellers are in the TARDIS? plugin.utils.updateTravellerCount(id); sender.sendMessage(plugin.pluginName + "The TARDIS is coming..."); long delay = 100L; if (plugin.getServer().getPluginManager().getPlugin("Spout") != null && SpoutManager.getPlayer(player).isSpoutCraftEnabled()) { SpoutManager.getSoundManager().playCustomSoundEffect(plugin, SpoutManager.getPlayer(player), "https://dl.dropbox.com/u/53758864/tardis_land.mp3", false, eyeLocation, 9, 75); delay = 400L; } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(oldSave, d); plugin.destroyPB.destroyTorch(oldSave); plugin.destroyPB.destroyPoliceBox(oldSave, d, id, false); plugin.buildPB.buildPoliceBox(id, eyeLocation, d, cham, p, false); } }, delay); // remove energy from TARDIS HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); qf.alterEnergyLevel("tardis", -ch, wheret, player); plugin.tardisHasDestination.remove(id); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("check_loc")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); tt.testSafeLocation(eyeLocation, d); return true; } if (args[0].equalsIgnoreCase("home")) { if (player.hasPermission("tardis.timetravel")) { Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS home in this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot set the TARDIS home location to this world"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot set the home locatopn here because you are inside a TARDIS!"); return true; } String sethome = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("home", sethome); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The new TARDIS home was set!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"door", "button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "chameleon", "save-sign", "artron", "handbrake", "condenser"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!Arrays.asList(validBlockNames).contains(args[1].toLowerCase(Locale.ENGLISH))) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : door|button|world-repeater|x-repeater|z-repeater|y-repeater|chameleon|save-sign|artron|handbrake|condenser"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } plugin.trackPlayers.put(player.getName(), args[1].toLowerCase(Locale.ENGLISH)); player.sendMessage(plugin.pluginName + "Click the TARDIS " + args[1].toLowerCase(Locale.ENGLISH) + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("bind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } int did; HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1]); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); QueryFactory qf = new QueryFactory(plugin); did = qf.doInsert("destinations", set); } else { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } } else { did = rsd.getDest_id(); } plugin.trackBinder.put(player.getName(), did); player.sendMessage(plugin.pluginName + "Click the block you want to bind to this save location."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("unbind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } if (rsd.getBind().equals("")) { sender.sendMessage(plugin.pluginName + "There is no button bound to that save name!"); return true; } int did = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("dest_id", did); if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { // delete the record qf.doDelete("destinations", whereb); } else { // just remove the bind location HashMap<String, Object> set = new HashMap<String, Object>(); set.put("bind", ""); qf.doUpdate("destinations", set, whereb); } player.sendMessage(plugin.pluginName + "The location was unbound. You can safely delete the block."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rebuild") || args[0].equalsIgnoreCase("hide")) { if (player.hasPermission("tardis.rebuild")) { String save; World w; int x, y, z, id; TARDISConstants.COMPASS d; boolean cham = false; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } id = rs.getTardis_id(); save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } d = rs.getDirection(); String[] save_data = save.split(":"); w = plugin.getServer().getWorld(save_data[0]); x = plugin.utils.parseNum(save_data[1]); y = plugin.utils.parseNum(save_data[2]); z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); if (args[0].equalsIgnoreCase("rebuild")) { plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was rebuilt!"); return true; } if (args[0].equalsIgnoreCase("hide")) { int level = rs.getArtron_level(); int hide = plugin.getConfig().getInt("hide"); if (level < hide) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to hide!"); return false; } // remove torch plugin.destroyPB.destroyTorch(l); // remove sign plugin.destroyPB.destroySign(l, d); // remove blue box plugin.destroyPB.destroyPoliceBox(l, d, id, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was hidden! Use " + ChatColor.GREEN + "/tardis rebuild" + ChatColor.RESET + " to show it again."); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); QueryFactory qf = new QueryFactory(plugin); qf.alterEnergyLevel("tardis", -hide, wheret, player); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("tardis.list")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2 || (!args[1].equalsIgnoreCase("saves") && !args[1].equalsIgnoreCase("companions") && !args[1].equalsIgnoreCase("areas") && !args[1].equalsIgnoreCase("rechargers"))) { sender.sendMessage(plugin.pluginName + "You need to specify which TARDIS list you want to view! [saves|companions|areas|rechargers]"); return false; } TARDISLister.list(player, args[1]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (player.hasPermission("tardis.find")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String loc = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] findData = loc.split(":"); sender.sendMessage(plugin.pluginName + "TARDIS was left at " + findData[0] + " at x: " + findData[1] + " y: " + findData[2] + " z: " + findData[3]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (comps != null && !comps.equals("")) { // add to the list String newList = comps + ":" + args[1].toLowerCase(Locale.ENGLISH); set.put("companions", newList); } else { // make a list set.put("companions", args[1].toLowerCase(Locale.ENGLISH)); } qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); if (comps == null || comps.equals("")) { sender.sendMessage(plugin.pluginName + "You have not added any TARDIS companions yet!"); return true; } } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { String[] split = comps.split(":"); StringBuilder buf = new StringBuilder(); String newList; if (split.length > 1) { // recompile string without the specified player for (String c : split) { if (!c.equals(args[1].toLowerCase(Locale.ENGLISH))) { // add to new string buf.append(c).append(":"); } } // remove trailing colon newList = buf.toString().substring(0, buf.length() - 1); } else { newList = ""; } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("companions", newList); qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid save name (it may be too long or contains spaces)."); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { String cur = rs.getCurrent(); String sav = rs.getSave(); int id = rs.getTardis_id(); String[] curDest; // get current destination HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (rst.resultSet() || plugin.tardisHasDestination.containsKey(id)) { // inside TARDIS curDest = cur.split(":"); } else { // outside TARDIS curDest = sav.split(":"); } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", curDest[0]); set.put("x", plugin.utils.parseNum(curDest[1])); set.put("y", plugin.utils.parseNum(curDest[2])); set.put("z", plugin.utils.parseNum(curDest[3])); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The location '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("removesave")) { if (player.hasPermission("tardis.save")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("dest_name", args[1]); whered.put("tardis_id", id); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a saved destination with that name!"); return false; } int destID = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> did = new HashMap<String, Object>(); did.put("dest_id", destID); qf.doDelete("destinations", did); sender.sendMessage(plugin.pluginName + "The destination " + args[1] + " was deleted!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("setdest")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "The destination name must be between 2 and 16 characters and have no spaces!"); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } // get location player is looking at Block b = player.getTargetBlock(transparent, 50); Location l = b.getLocation(); String world = l.getWorld().getName(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && world.equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS destination to this world!"); return true; } // check the world is not excluded if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, l, true)) { return true; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, l)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to save the TARDIS to this location!"); return false; } } String dw = l.getWorld().getName(); int dx = l.getBlockX(); int dy = l.getBlockY() + 1; int dz = l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", dw); set.put("x", dx); set.put("y", dy); set.put("z", dz); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The destination '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("direction")) { if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("north") && !args[1].equalsIgnoreCase("west") && !args[1].equalsIgnoreCase("south") && !args[1].equalsIgnoreCase("east"))) { sender.sendMessage(plugin.pluginName + "You need to specify the compass direction e.g. north, west, south or east!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] save_data = save.split(":"); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } boolean cham = false; if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } String dir = args[1].toUpperCase(Locale.ENGLISH); TARDISConstants.COMPASS old_d = rs.getDirection(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("direction", dir); qf.doUpdate("tardis", set, tid); HashMap<String, Object> did = new HashMap<String, Object>(); HashMap<String, Object> setd = new HashMap<String, Object>(); did.put("door_type", 0); did.put("tardis_id", id); setd.put("door_direction", dir); qf.doUpdate("doors", setd, did); World w = plugin.getServer().getWorld(save_data[0]); int x = plugin.utils.parseNum(save_data[1]); int y = plugin.utils.parseNum(save_data[2]); int z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(dir); // destroy platform plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(l, old_d); plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("namekey")) { if (bukkitversion.compareTo(preIMversion) < 0 || (bukkitversion.compareTo(preIMversion) == 0 && SUBversion.compareTo(preSUBversion) < 0)) { sender.sendMessage(plugin.pluginName + "You cannot rename the TARDIS key with this version of Bukkit!"); return true; } Material m = Material.getMaterial(plugin.getConfig().getString("key")); ItemStack is = player.getItemInHand(); if (!is.getType().equals(m)) { sender.sendMessage(plugin.pluginName + "You can only rename the TARDIS key!"); return true; } int count = args.length; if (count < 2) { return false; } StringBuilder buf = new StringBuilder(args[1]); for (int i = 2; i < count; i++) { buf.append(" ").append(args[i]); } String tmp = buf.toString(); TARDISItemRenamer ir = new TARDISItemRenamer(is); ir.setName(tmp, false); sender.sendMessage(plugin.pluginName + "TARDIS key renamed to '" + tmp + "'"); return true; } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } if (args.length == 2) { List<String> cmds = new ArrayList<String>(); for (TARDISConstants.CMDS c : TARDISConstants.CMDS.values()) { cmds.add(c.toString()); } // check that the second arument is valid if (!cmds.contains(args[1].toUpperCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That is not a valid help topic!"); return true; } switch (TARDISConstants.fromString(args[1])) { case CREATE: sender.sendMessage(TARDISConstants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(TARDISConstants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(TARDISConstants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(TARDISConstants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(TARDISConstants.COMMAND_SAVE.split("\n")); break; case REMOVESAVE: sender.sendMessage(TARDISConstants.COMMAND_REMOVESAVE.split("\n")); break; case ADD: sender.sendMessage(TARDISConstants.COMMAND_ADD.split("\n")); break; case TRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TRAVEL.split("\n")); break; case UPDATE: sender.sendMessage(TARDISConstants.COMMAND_UPDATE.split("\n")); break; case REBUILD: sender.sendMessage(TARDISConstants.COMMAND_REBUILD.split("\n")); break; case CHAMELEON: sender.sendMessage(TARDISConstants.COMMAND_CHAMELEON.split("\n")); break; case SFX: sender.sendMessage(TARDISConstants.COMMAND_SFX.split("\n")); break; case PLATFORM: sender.sendMessage(TARDISConstants.COMMAND_PLATFORM.split("\n")); break; case SETDEST: sender.sendMessage(TARDISConstants.COMMAND_SETDEST.split("\n")); break; case HOME: sender.sendMessage(TARDISConstants.COMMAND_HOME.split("\n")); break; case HIDE: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case VERSION: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case ADMIN: sender.sendMessage(TARDISConstants.COMMAND_ADMIN.split("\n")); break; case AREA: sender.sendMessage(TARDISConstants.COMMAND_AREA.split("\n")); break; case ROOM: sender.sendMessage(TARDISConstants.COMMAND_ROOM.split("\n")); break; case ARTRON: sender.sendMessage(TARDISConstants.COMMAND_ARTRON.split("\n")); break; case BIND: sender.sendMessage(TARDISConstants.COMMAND_BIND.split("\n")); break; default: sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); } } return true; } } } // If the above has happened the function will break and return true. if this hasn't happened then value of false will be returned. return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardis then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } // the command list - first argument MUST appear here! if (!firstArgs.contains(args[0].toLowerCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That command wasn't recognised type " + ChatColor.GREEN + "/tardis help" + ChatColor.RESET + " to see the commands"); return false; } // temporary command to convert old gravity well to new style if (args[0].equalsIgnoreCase("gravity")) { if (player == null) { sender.sendMessage(plugin.pluginName + "Must be a player"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); try { TARDISDatabase service = TARDISDatabase.getInstance(); Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM gravity WHERE tardis_id = " + id; ResultSet rsg = statement.executeQuery(query); if (rsg.isBeforeFirst()) { // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14,y=10.0,z=27,pitch=0.0,yaw=0.0} // Location{world=CraftWorld{name=TARDIS_WORLD_eccentric_nz},x=-14.0,y=10.0,z=5.0,pitch=0.0,yaw=0.0} String up = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("upx") + ",y=10.0,z=" + rsg.getFloat("upz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityUpList.add(up); String down = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("downx") + ",y=10.0,z=" + rsg.getFloat("downz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityDownList.add(down); HashMap<String, Object> setu = new HashMap<String, Object>(); setu.put("tardis_id", id); setu.put("location", up); setu.put("direction", 1); HashMap<String, Object> setd = new HashMap<String, Object>(); setd.put("tardis_id", id); setd.put("location", down); setd.put("direction", 0); QueryFactory qf = new QueryFactory(plugin); qf.doInsert("gravity_well", setu); qf.doInsert("gravity_well", setd); player.sendMessage(plugin.pluginName + "Gravity well converted successfully."); return true; } } catch (SQLException e) { plugin.debug("Gravity conversion error: " + e.getMessage()); } } if (args[0].equalsIgnoreCase("version")) { FileConfiguration pluginYml = YamlConfiguration.loadConfiguration(plugin.pm.getPlugin("TARDIS").getResource("plugin.yml")); String version = pluginYml.getString("version"); String cb = Bukkit.getVersion(); sender.sendMessage(plugin.pluginName + "You are running TARDIS version: " + ChatColor.AQUA + version + ChatColor.RESET + " with CraftBukkit " + cb); // also check if there is an update if (plugin.getConfig().getBoolean("check_for_updates")) { TARDISUpdateChecker update = new TARDISUpdateChecker(plugin); update.checkVersion(player); } return true; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("chameleon")) { if (!plugin.getConfig().getBoolean("chameleon")) { sender.sendMessage(plugin.pluginName + "This server does not allow the use of the chameleon circuit!"); return false; } if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("on") && !args[1].equalsIgnoreCase("off"))) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String chamStr = rs.getChameleon(); if (chamStr.equals("")) { sender.sendMessage(plugin.pluginName + "Could not find the Chameleon Circuit!"); return false; } else { int x, y, z; String[] chamData = chamStr.split(":"); World w = plugin.getServer().getWorld(chamData[0]); TARDISConstants.COMPASS d = rs.getDirection(); x = plugin.utils.parseNum(chamData[1]); y = plugin.utils.parseNum(chamData[2]); z = plugin.utils.parseNum(chamData[3]); Block chamBlock = w.getBlockAt(x, y, z); Material chamType = chamBlock.getType(); if (chamType == Material.WALL_SIGN || chamType == Material.SIGN_POST) { Sign cs = (Sign) chamBlock.getState(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (args[1].equalsIgnoreCase("on")) { set.put("chamele_on", 1); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned ON!"); cs.setLine(3, ChatColor.GREEN + "ON"); } if (args[1].equalsIgnoreCase("off")) { set.put("chamele_on", 0); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned OFF."); cs.setLine(3, ChatColor.RED + "OFF"); } cs.update(); } } return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("room")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: passage|arboretum|pool|vault|kitchen|bedroom|library|workshop|empty|gravity"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } String chunk = rs.getChunk(); String[] data = chunk.split(":"); World room_world = plugin.getServer().getWorld(data[0]); ChunkGenerator gen = room_world.getGenerator(); WorldType wt = room_world.getWorldType(); boolean special = (data[0].contains("TARDIS_TimeVortex") && (wt.equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator)); if (!data[0].contains("TARDIS_WORLD_") && !special) { player.sendMessage(plugin.pluginName + "You cannot grow rooms unless your TARDIS was created in its own world!"); return true; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } // check they have enough artron energy if (level < plugin.getConfig().getInt("rooms." + room + ".cost")) { player.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to grow this room!"); return true; } String message; // if it is a gravity well if (room.equals("GRAVITY")) { message = "Place the GRAVITY WELL seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") into the centre of the floor in an empty room, then hit it with the TARDIS key to start growing your room!"; } else { message = "Place the " + room + " seed block (" + plugin.getConfig().getString("rooms." + room + ".seed") + ") where the door should be, then hit it with the TARDIS key to start growing your room!"; } plugin.trackRoomSeed.put(player.getName(), room); player.sendMessage(plugin.pluginName + message); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("jettison")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (room.equals("GRAVITY")) { player.sendMessage(plugin.pluginName + "You cannot jettison gravity wells!"); return true; } if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of : passage|arboretum|pool|vault|kitchen|bedroom|library|empty"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } int id = rs.getTardis_id(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } plugin.trackJettison.put(player.getName(), room); player.sendMessage(plugin.pluginName + "Stand in the doorway of the room you want to jettison and place a TNT block directly in front of the door. Hit the TNT with the TARDIS key to jettison the room!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("occupy")) { if (player.hasPermission("tardis.timetravel")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + " You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); String occupied; QueryFactory qf = new QueryFactory(plugin); if (rst.resultSet()) { HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("player", player.getName()); qf.doDelete("travellers", whered); occupied = ChatColor.RED + "UNOCCUPIED"; } else { HashMap<String, Object> wherei = new HashMap<String, Object>(); wherei.put("tardis_id", id); wherei.put("player", player.getName()); qf.doInsert("travellers", wherei); occupied = ChatColor.GREEN + "OCCUPIED"; } sender.sendMessage(plugin.pluginName + " TARDIS occupation was set to: " + occupied); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("comehere")) { if (player.hasPermission("tardis.timetravel")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to bring the TARDIS to this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return false; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, eyeLocation)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to bring the TARDIS to this location!"); return false; } } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); final ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return true; } final int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); int[] start_loc = tt.getStartLocation(eyeLocation, d); // safeLocation(int startx, int starty, int startz, int resetx, int resetz, World w, TARDISConstants.COMPASS d) int count = tt.safeLocation(start_loc[0], eyeLocation.getBlockY(), start_loc[2], start_loc[1], start_loc[3], eyeLocation.getWorld(), d); if (count > 0) { sender.sendMessage(plugin.pluginName + "That location would grief existing blocks! Try somewhere else!"); return true; } int level = rs.getArtron_level(); int ch = plugin.getConfig().getInt("comehere"); if (level < ch) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!"); return true; } final Player p = player; String badsave = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); boolean chamtmp = false; if (plugin.getConfig().getBoolean("chameleon")) { chamtmp = rs.isChamele_on(); } final boolean cham = chamtmp; String[] saveData = badsave.split(":"); World w = plugin.getServer().getWorld(saveData[0]); int x, y, z; x = plugin.utils.parseNum(saveData[1]); y = plugin.utils.parseNum(saveData[2]); z = plugin.utils.parseNum(saveData[3]); final Location oldSave = w.getBlockAt(x, y, z).getLocation(); //rs.close(); String comehere = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", comehere); set.put("current", comehere); qf.doUpdate("tardis", set, tid); // how many travellers are in the TARDIS? plugin.utils.updateTravellerCount(id); sender.sendMessage(plugin.pluginName + "The TARDIS is coming..."); long delay = 100L; if (plugin.getServer().getPluginManager().getPlugin("Spout") != null && SpoutManager.getPlayer(player).isSpoutCraftEnabled()) { SpoutManager.getSoundManager().playCustomSoundEffect(plugin, SpoutManager.getPlayer(player), "https://dl.dropbox.com/u/53758864/tardis_land.mp3", false, eyeLocation, 9, 75); delay = 400L; } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(oldSave, d); plugin.destroyPB.destroyTorch(oldSave); plugin.destroyPB.destroyPoliceBox(oldSave, d, id, false); plugin.buildPB.buildPoliceBox(id, eyeLocation, d, cham, p, false); } }, delay); // remove energy from TARDIS HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); qf.alterEnergyLevel("tardis", -ch, wheret, player); plugin.tardisHasDestination.remove(id); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("check_loc")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimetravel tt = new TARDISTimetravel(plugin); tt.testSafeLocation(eyeLocation, d); return true; } if (args[0].equalsIgnoreCase("home")) { if (player.hasPermission("tardis.timetravel")) { Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS home in this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot set the TARDIS home location to this world"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot set the home locatopn here because you are inside a TARDIS!"); return true; } String sethome = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("home", sethome); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The new TARDIS home was set!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"door", "button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "chameleon", "save-sign", "artron", "handbrake", "condenser"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!Arrays.asList(validBlockNames).contains(args[1].toLowerCase(Locale.ENGLISH))) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : door|button|world-repeater|x-repeater|z-repeater|y-repeater|chameleon|save-sign|artron|handbrake|condenser"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } plugin.trackPlayers.put(player.getName(), args[1].toLowerCase(Locale.ENGLISH)); player.sendMessage(plugin.pluginName + "Click the TARDIS " + args[1].toLowerCase(Locale.ENGLISH) + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("bind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } int did; HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1]); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); QueryFactory qf = new QueryFactory(plugin); did = qf.doInsert("destinations", set); } else { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } } else { did = rsd.getDest_id(); } plugin.trackBinder.put(player.getName(), did); player.sendMessage(plugin.pluginName + "Click the block you want to bind to this save location."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("unbind")) { if (player.hasPermission("tardis.update")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("tardis_id", id); whered.put("dest_name", args[1].toLowerCase(Locale.ENGLISH)); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a save with that name! Try using " + ChatColor.AQUA + "/tardis list saves" + ChatColor.RESET + " first."); return true; } if (rsd.getBind().equals("")) { sender.sendMessage(plugin.pluginName + "There is no button bound to that save name!"); return true; } int did = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("dest_id", did); if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { // delete the record qf.doDelete("destinations", whereb); } else { // just remove the bind location HashMap<String, Object> set = new HashMap<String, Object>(); set.put("bind", ""); qf.doUpdate("destinations", set, whereb); } player.sendMessage(plugin.pluginName + "The location was unbound. You can safely delete the block."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rebuild") || args[0].equalsIgnoreCase("hide")) { if (player.hasPermission("tardis.rebuild")) { String save; World w; int x, y, z, id; TARDISConstants.COMPASS d; boolean cham = false; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } id = rs.getTardis_id(); save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } d = rs.getDirection(); String[] save_data = save.split(":"); w = plugin.getServer().getWorld(save_data[0]); x = plugin.utils.parseNum(save_data[1]); y = plugin.utils.parseNum(save_data[2]); z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); if (args[0].equalsIgnoreCase("rebuild")) { plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was rebuilt!"); return true; } if (args[0].equalsIgnoreCase("hide")) { int level = rs.getArtron_level(); int hide = plugin.getConfig().getInt("hide"); if (level < hide) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to hide!"); return false; } // remove torch plugin.destroyPB.destroyTorch(l); // remove sign plugin.destroyPB.destroySign(l, d); // remove blue box plugin.destroyPB.destroyPoliceBox(l, d, id, true); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was hidden! Use " + ChatColor.GREEN + "/tardis rebuild" + ChatColor.RESET + " to show it again."); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); QueryFactory qf = new QueryFactory(plugin); qf.alterEnergyLevel("tardis", -hide, wheret, player); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("tardis.list")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2 || (!args[1].equalsIgnoreCase("saves") && !args[1].equalsIgnoreCase("companions") && !args[1].equalsIgnoreCase("areas") && !args[1].equalsIgnoreCase("rechargers"))) { sender.sendMessage(plugin.pluginName + "You need to specify which TARDIS list you want to view! [saves|companions|areas|rechargers]"); return false; } TARDISLister.list(player, args[1]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (player.hasPermission("tardis.find")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String loc = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] findData = loc.split(":"); sender.sendMessage(plugin.pluginName + "TARDIS was left at " + findData[0] + " at x: " + findData[1] + " y: " + findData[2] + " z: " + findData[3]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (comps != null && !comps.equals("")) { // add to the list String newList = comps + ":" + args[1].toLowerCase(Locale.ENGLISH); set.put("companions", newList); } else { // make a list set.put("companions", args[1].toLowerCase(Locale.ENGLISH)); } qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); if (comps == null || comps.equals("")) { sender.sendMessage(plugin.pluginName + "You have not added any TARDIS companions yet!"); return true; } } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { String[] split = comps.split(":"); StringBuilder buf = new StringBuilder(); String newList; if (split.length > 1) { // recompile string without the specified player for (String c : split) { if (!c.equals(args[1].toLowerCase(Locale.ENGLISH))) { // add to new string buf.append(c).append(":"); } } // remove trailing colon newList = buf.toString().substring(0, buf.length() - 1); } else { newList = ""; } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("companions", newList); qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid save name (it may be too long or contains spaces)."); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { String cur = rs.getCurrent(); String sav = rs.getSave(); int id = rs.getTardis_id(); String[] curDest; // get current destination HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (rst.resultSet() || plugin.tardisHasDestination.containsKey(id)) { // inside TARDIS curDest = cur.split(":"); } else { // outside TARDIS curDest = sav.split(":"); } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", curDest[0]); set.put("x", plugin.utils.parseNum(curDest[1])); set.put("y", plugin.utils.parseNum(curDest[2])); set.put("z", plugin.utils.parseNum(curDest[3])); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The location '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("removesave")) { if (player.hasPermission("tardis.save")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("dest_name", args[1]); whered.put("tardis_id", id); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a saved destination with that name!"); return false; } int destID = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> did = new HashMap<String, Object>(); did.put("dest_id", destID); qf.doDelete("destinations", did); sender.sendMessage(plugin.pluginName + "The destination " + args[1] + " was deleted!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("setdest")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "The destination name must be between 2 and 16 characters and have no spaces!"); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } // get location player is looking at Block b = player.getTargetBlock(transparent, 50); Location l = b.getLocation(); String world = l.getWorld().getName(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && world.equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS destination to this world!"); return true; } // check the world is not excluded if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, l, true)) { return true; } if (player.hasPermission("tardis.exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, l)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to save the TARDIS to this location!"); return false; } } String dw = l.getWorld().getName(); int dx = l.getBlockX(); int dy = l.getBlockY() + 1; int dz = l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", dw); set.put("x", dx); set.put("y", dy); set.put("z", dz); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The destination '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("direction")) { if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("north") && !args[1].equalsIgnoreCase("west") && !args[1].equalsIgnoreCase("south") && !args[1].equalsIgnoreCase("east"))) { sender.sendMessage(plugin.pluginName + "You need to specify the compass direction e.g. north, west, south or east!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String save = (plugin.tardisHasDestination.containsKey(id)) ? rs.getCurrent() : rs.getSave(); String[] save_data = save.split(":"); if (plugin.tardisMaterialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } boolean cham = false; if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } String dir = args[1].toUpperCase(Locale.ENGLISH); TARDISConstants.COMPASS old_d = rs.getDirection(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("direction", dir); qf.doUpdate("tardis", set, tid); HashMap<String, Object> did = new HashMap<String, Object>(); HashMap<String, Object> setd = new HashMap<String, Object>(); did.put("door_type", 0); did.put("tardis_id", id); setd.put("door_direction", dir); qf.doUpdate("doors", setd, did); World w = plugin.getServer().getWorld(save_data[0]); int x = plugin.utils.parseNum(save_data[1]); int y = plugin.utils.parseNum(save_data[2]); int z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(dir); // destroy platform plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(l, old_d); plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("namekey")) { if (bukkitversion.compareTo(preIMversion) < 0 || (bukkitversion.compareTo(preIMversion) == 0 && SUBversion.compareTo(preSUBversion) < 0)) { sender.sendMessage(plugin.pluginName + "You cannot rename the TARDIS key with this version of Bukkit!"); return true; } Material m = Material.getMaterial(plugin.getConfig().getString("key")); ItemStack is = player.getItemInHand(); if (!is.getType().equals(m)) { sender.sendMessage(plugin.pluginName + "You can only rename the TARDIS key!"); return true; } int count = args.length; if (count < 2) { return false; } StringBuilder buf = new StringBuilder(args[1]); for (int i = 2; i < count; i++) { buf.append(" ").append(args[i]); } String tmp = buf.toString(); TARDISItemRenamer ir = new TARDISItemRenamer(is); ir.setName(tmp, false); sender.sendMessage(plugin.pluginName + "TARDIS key renamed to '" + tmp + "'"); return true; } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } if (args.length == 2) { List<String> cmds = new ArrayList<String>(); for (TARDISConstants.CMDS c : TARDISConstants.CMDS.values()) { cmds.add(c.toString()); } // check that the second arument is valid if (!cmds.contains(args[1].toUpperCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That is not a valid help topic!"); return true; } switch (TARDISConstants.fromString(args[1])) { case CREATE: sender.sendMessage(TARDISConstants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(TARDISConstants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(TARDISConstants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(TARDISConstants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(TARDISConstants.COMMAND_SAVE.split("\n")); break; case REMOVESAVE: sender.sendMessage(TARDISConstants.COMMAND_REMOVESAVE.split("\n")); break; case ADD: sender.sendMessage(TARDISConstants.COMMAND_ADD.split("\n")); break; case TRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TRAVEL.split("\n")); break; case UPDATE: sender.sendMessage(TARDISConstants.COMMAND_UPDATE.split("\n")); break; case REBUILD: sender.sendMessage(TARDISConstants.COMMAND_REBUILD.split("\n")); break; case CHAMELEON: sender.sendMessage(TARDISConstants.COMMAND_CHAMELEON.split("\n")); break; case SFX: sender.sendMessage(TARDISConstants.COMMAND_SFX.split("\n")); break; case PLATFORM: sender.sendMessage(TARDISConstants.COMMAND_PLATFORM.split("\n")); break; case SETDEST: sender.sendMessage(TARDISConstants.COMMAND_SETDEST.split("\n")); break; case HOME: sender.sendMessage(TARDISConstants.COMMAND_HOME.split("\n")); break; case HIDE: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case VERSION: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case ADMIN: sender.sendMessage(TARDISConstants.COMMAND_ADMIN.split("\n")); break; case AREA: sender.sendMessage(TARDISConstants.COMMAND_AREA.split("\n")); break; case ROOM: sender.sendMessage(TARDISConstants.COMMAND_ROOM.split("\n")); break; case ARTRON: sender.sendMessage(TARDISConstants.COMMAND_ARTRON.split("\n")); break; case BIND: sender.sendMessage(TARDISConstants.COMMAND_BIND.split("\n")); break; default: sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); } } return true; } } } // If the above has happened the function will break and return true. if this hasn't happened then value of false will be returned. return false; }
diff --git a/src/com/dunksoftware/seminoletix/LoginActivity.java b/src/com/dunksoftware/seminoletix/LoginActivity.java index 4b7fa0e..bb94f8b 100644 --- a/src/com/dunksoftware/seminoletix/LoginActivity.java +++ b/src/com/dunksoftware/seminoletix/LoginActivity.java @@ -1,205 +1,210 @@ package com.dunksoftware.seminoletix; import java.util.concurrent.ExecutionException; import android.content.DialogInterface; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class LoginActivity extends Activity { public static final String PREFS_NAME = "TixSettingsFile"; public static final String USER_NAME = "username"; public static final String ERROR_STRING = "error"; private EditText editUsername, editPassword; private Button mRegisterBtn, mLoginBtn; private String mUserResponse, mPassResponse; private UserControl mUserControl; private UserControl.Login Login; public static final int NO_CONNECTION_DIALOG = 80; public static boolean remembered = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( remembered ) { // go to next page startActivity(new Intent(this, ListActivity.class)); } else { // display the login screen and proceed setContentView(R.layout.activity_login); mUserControl = new UserControl(); // link widgets to variables editUsername = (EditText)findViewById(R.id.UI_EditFSUID); editPassword = (EditText)findViewById(R.id.UI_EditFSUPass); mRegisterBtn = (Button)findViewById(R.id.UI_registerBtn); mLoginBtn = (Button)findViewById(R.id.UI_signinBtn); // set anonymous on_click listeners for registration and login buttons mLoginBtn.setOnClickListener( new View.OnClickListener() { // email, cardNum, password, remember_me @SuppressWarnings("deprecation") @Override public void onClick(View v) { mUserResponse = editUsername.getText().toString(); mPassResponse = editPassword.getText().toString(); if( ((CheckBox)findViewById(R.id.UI_CheckRememberMe)).isChecked()) { Login = mUserControl.new Login(mUserResponse, mPassResponse, true); ShowMessage("You will be remembered.", Toast.LENGTH_SHORT); remembered = true; } if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Login = mUserControl.new Login(mUserResponse, mPassResponse, false); Login.execute(); try { JSONObject JSONresponse = new JSONObject(Login.get()); // Send the user back to the login page. if( JSONresponse.getString("success").equals("true")) { // force the virtual keyboard off the screen InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editPassword.getWindowToken(), 0); startActivity(new Intent(getApplicationContext(), ListActivity.class)); //ShowMessage(JSONresponse.toString(), Toast.LENGTH_LONG); /* Close the current activity, ensuring that this * SAME page cannot be reached via Back button, * once a user has successfully registered. * (Basically takes this page out of the "page history" ) */ //finish(); } + // If the user is already logged in, just go back to the list. + else if( JSONresponse.getString("success").equals("false") && + JSONresponse.getString("message").equals("Already logged in.")) { + startActivity(new Intent(getApplicationContext(), ListActivity.class)); + } /* if server returns false on registration, clear the CardNumber * and PIN field */ else { // Print out a success message to the user's UI ShowMessage( JSONresponse.getString("message"), Toast.LENGTH_LONG); editUsername.getText().clear(); editPassword.getText().clear(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } }); // Event handler for the Register button mRegisterBtn.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View arg0) { if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Intent nextActivityIntent = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(nextActivityIntent); } } }); } } // End of onCreate function @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_login, menu); return true; } @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder; switch( id ) { case NO_CONNECTION_DIALOG: { builder = new AlertDialog. Builder(this); builder.setCancelable(false).setTitle("Connection Error"). setMessage(R.string.Error_NoConnection).setNeutralButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(NO_CONNECTION_DIALOG); finish(); } }); builder.create().show(); break; } } return super.onCreateDialog(id); } void ShowMessage(String message, int length) { Toast.makeText(getApplicationContext(), message, length).show(); } private boolean Online() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( remembered ) { // go to next page startActivity(new Intent(this, ListActivity.class)); } else { // display the login screen and proceed setContentView(R.layout.activity_login); mUserControl = new UserControl(); // link widgets to variables editUsername = (EditText)findViewById(R.id.UI_EditFSUID); editPassword = (EditText)findViewById(R.id.UI_EditFSUPass); mRegisterBtn = (Button)findViewById(R.id.UI_registerBtn); mLoginBtn = (Button)findViewById(R.id.UI_signinBtn); // set anonymous on_click listeners for registration and login buttons mLoginBtn.setOnClickListener( new View.OnClickListener() { // email, cardNum, password, remember_me @SuppressWarnings("deprecation") @Override public void onClick(View v) { mUserResponse = editUsername.getText().toString(); mPassResponse = editPassword.getText().toString(); if( ((CheckBox)findViewById(R.id.UI_CheckRememberMe)).isChecked()) { Login = mUserControl.new Login(mUserResponse, mPassResponse, true); ShowMessage("You will be remembered.", Toast.LENGTH_SHORT); remembered = true; } if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Login = mUserControl.new Login(mUserResponse, mPassResponse, false); Login.execute(); try { JSONObject JSONresponse = new JSONObject(Login.get()); // Send the user back to the login page. if( JSONresponse.getString("success").equals("true")) { // force the virtual keyboard off the screen InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editPassword.getWindowToken(), 0); startActivity(new Intent(getApplicationContext(), ListActivity.class)); //ShowMessage(JSONresponse.toString(), Toast.LENGTH_LONG); /* Close the current activity, ensuring that this * SAME page cannot be reached via Back button, * once a user has successfully registered. * (Basically takes this page out of the "page history" ) */ //finish(); } /* if server returns false on registration, clear the CardNumber * and PIN field */ else { // Print out a success message to the user's UI ShowMessage( JSONresponse.getString("message"), Toast.LENGTH_LONG); editUsername.getText().clear(); editPassword.getText().clear(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } }); // Event handler for the Register button mRegisterBtn.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View arg0) { if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Intent nextActivityIntent = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(nextActivityIntent); } } }); } } // End of onCreate function
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( remembered ) { // go to next page startActivity(new Intent(this, ListActivity.class)); } else { // display the login screen and proceed setContentView(R.layout.activity_login); mUserControl = new UserControl(); // link widgets to variables editUsername = (EditText)findViewById(R.id.UI_EditFSUID); editPassword = (EditText)findViewById(R.id.UI_EditFSUPass); mRegisterBtn = (Button)findViewById(R.id.UI_registerBtn); mLoginBtn = (Button)findViewById(R.id.UI_signinBtn); // set anonymous on_click listeners for registration and login buttons mLoginBtn.setOnClickListener( new View.OnClickListener() { // email, cardNum, password, remember_me @SuppressWarnings("deprecation") @Override public void onClick(View v) { mUserResponse = editUsername.getText().toString(); mPassResponse = editPassword.getText().toString(); if( ((CheckBox)findViewById(R.id.UI_CheckRememberMe)).isChecked()) { Login = mUserControl.new Login(mUserResponse, mPassResponse, true); ShowMessage("You will be remembered.", Toast.LENGTH_SHORT); remembered = true; } if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Login = mUserControl.new Login(mUserResponse, mPassResponse, false); Login.execute(); try { JSONObject JSONresponse = new JSONObject(Login.get()); // Send the user back to the login page. if( JSONresponse.getString("success").equals("true")) { // force the virtual keyboard off the screen InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editPassword.getWindowToken(), 0); startActivity(new Intent(getApplicationContext(), ListActivity.class)); //ShowMessage(JSONresponse.toString(), Toast.LENGTH_LONG); /* Close the current activity, ensuring that this * SAME page cannot be reached via Back button, * once a user has successfully registered. * (Basically takes this page out of the "page history" ) */ //finish(); } // If the user is already logged in, just go back to the list. else if( JSONresponse.getString("success").equals("false") && JSONresponse.getString("message").equals("Already logged in.")) { startActivity(new Intent(getApplicationContext(), ListActivity.class)); } /* if server returns false on registration, clear the CardNumber * and PIN field */ else { // Print out a success message to the user's UI ShowMessage( JSONresponse.getString("message"), Toast.LENGTH_LONG); editUsername.getText().clear(); editPassword.getText().clear(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } }); // Event handler for the Register button mRegisterBtn.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View arg0) { if( !Online() ) showDialog(NO_CONNECTION_DIALOG); else { Intent nextActivityIntent = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(nextActivityIntent); } } }); } } // End of onCreate function
diff --git a/ide-test/org.codehaus.groovy.alltests/src/org/codehaus/groovy/alltests/SanityTest.java b/ide-test/org.codehaus.groovy.alltests/src/org/codehaus/groovy/alltests/SanityTest.java index ea03018ca..0e65b69e6 100644 --- a/ide-test/org.codehaus.groovy.alltests/src/org/codehaus/groovy/alltests/SanityTest.java +++ b/ide-test/org.codehaus.groovy.alltests/src/org/codehaus/groovy/alltests/SanityTest.java @@ -1,57 +1,59 @@ /* * Copyright 2011 SpringSource, a division of VMware, Inc * * andrew - Initial API and implementation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.alltests; import junit.framework.TestCase; import org.codehaus.groovy.eclipse.core.compiler.CompilerUtils; import org.codehaus.groovy.frameworkadapter.util.CompilerLevelUtils; import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; import org.osgi.framework.Version; /** * Ensure the proper compiler level is being run * @author Andrew Eisenberg * @created Jun 28, 2012 */ public class SanityTest extends TestCase { private Version getEclipseVersion() { Bundle jdtcore = Platform.getBundle("org.eclipse.jdt.core"); assertNotNull("Can't find jdt core", jdtcore); return jdtcore.getVersion(); } private Version getGroovyCompilerVersion() { return CompilerUtils.getActiveGroovyBundle().getVersion(); } public void testCompilerVersion() throws Exception { Version jdtVersion = getEclipseVersion(); Version groovyVersion = getGroovyCompilerVersion(); + // JDT 3.7 and 3.8 test against Groovy 2.0 + // JDT 3.9 test against Groovy 2.1 if (jdtVersion.getMinor() == 8 || jdtVersion.getMinor() == 7) { assertEquals(2, groovyVersion.getMajor()); assertEquals(0, groovyVersion.getMinor()); } else if (jdtVersion.getMinor() == 9) { assertEquals(2, groovyVersion.getMajor()); assertEquals(1, groovyVersion.getMinor()); } } }
true
true
public void testCompilerVersion() throws Exception { Version jdtVersion = getEclipseVersion(); Version groovyVersion = getGroovyCompilerVersion(); if (jdtVersion.getMinor() == 8 || jdtVersion.getMinor() == 7) { assertEquals(2, groovyVersion.getMajor()); assertEquals(0, groovyVersion.getMinor()); } else if (jdtVersion.getMinor() == 9) { assertEquals(2, groovyVersion.getMajor()); assertEquals(1, groovyVersion.getMinor()); } }
public void testCompilerVersion() throws Exception { Version jdtVersion = getEclipseVersion(); Version groovyVersion = getGroovyCompilerVersion(); // JDT 3.7 and 3.8 test against Groovy 2.0 // JDT 3.9 test against Groovy 2.1 if (jdtVersion.getMinor() == 8 || jdtVersion.getMinor() == 7) { assertEquals(2, groovyVersion.getMajor()); assertEquals(0, groovyVersion.getMinor()); } else if (jdtVersion.getMinor() == 9) { assertEquals(2, groovyVersion.getMajor()); assertEquals(1, groovyVersion.getMinor()); } }
diff --git a/JavaSource/org/unitime/timetable/webutil/EventEmail.java b/JavaSource/org/unitime/timetable/webutil/EventEmail.java index a0d1e3be..c0e58636 100644 --- a/JavaSource/org/unitime/timetable/webutil/EventEmail.java +++ b/JavaSource/org/unitime/timetable/webutil/EventEmail.java @@ -1,311 +1,311 @@ package org.unitime.timetable.webutil; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.StringTokenizer; import java.util.TreeSet; import javax.mail.Authenticator; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.unitime.commons.User; import org.unitime.commons.web.Web; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.model.Event; import org.unitime.timetable.model.EventNote; import org.unitime.timetable.model.Roles; import org.unitime.timetable.model.Event.MultiMeeting; import org.unitime.timetable.util.Constants; public class EventEmail { private static Log sLog = LogFactory.getLog(EventEmail.class); private Event iEvent = null; private TreeSet<MultiMeeting> iMeetings = null; private String iNote = null; private int iAction = sActionCreate; public static final int sActionCreate = 0; public static final int sActionApprove = 1; public static final int sActionReject = 2; public static final int sActionAddMeeting = 3; public static final int sActionUpdate = 4; public static final int sActionDelete = 5; public EventEmail(Event event, int action, TreeSet<MultiMeeting> meetings, String note) { iEvent = event; iAction = action; iMeetings = meetings; iNote = note; } public void send(HttpServletRequest request) { String subject = null; File conf = null; try { User user = Web.getUser(request.getSession()); if (Roles.ADMIN_ROLE.equals(user.getRole()) || Roles.EVENT_MGR_ROLE.equals(user.getRole())) { if (iAction!=sActionReject && iAction!=sActionApprove) return; } switch (iAction) { case sActionCreate : subject = "Event "+iEvent.getEventName()+" created."; break; case sActionApprove : subject = "Event "+iEvent.getEventName()+" approved."; break; case sActionReject : subject = "Event "+iEvent.getEventName()+" rejected."; break; case sActionUpdate : subject = "Event "+iEvent.getEventName()+" updated."; break; case sActionAddMeeting : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings added)."; break; case sActionDelete : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings deleted)."; break; } if (!"true".equals(ApplicationProperties.getProperty("tmtbl.event.confirmationEmail","true"))) { request.getSession().setAttribute(Constants.REQUEST_MSSG, "Confirmation emails are disabled."); return; } String message = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; message += "<html><head>"; message += "<title>"+subject+"</title>"; message += "<meta http-equiv='Content-Type' content='text/html; charset=windows-1250'>"; message += "<meta name='Author' content='UniTime LLC'>"; message += "<style type='text/css'>"; message += "<!--" + "A:link { color: blue; text-decoration: none; }" + "A:visited { color: blue; text-decoration: none; }" + "A:active { color: blue; text-decoration: none; }" + "A:hover { color: blue; text-decoration: none; }" + "-->"; message += "</style></head><body bgcolor='#ffffff' style='font-size: 10pt; font-family: arial;'>"; message += "<table border='0' width='95%' align='center' cellspacing='10'>"; message += "<tr><td colspan='2' style='border-bottom: 2px #2020FF solid;'><font size='+2'>"; message += iEvent.getEventName(); message += "</td></tr>"; message += "<tr><td>Event Type</td><td>"+iEvent.getEventTypeLabel()+"</td></tr>"; if (iEvent.getMinCapacity()!=null) { message += "<tr><td>"+(iEvent.getEventType()==Event.sEventTypeSpecial?"Expected Size":"Event Capacity")+":</td>"; if (iEvent.getMaxCapacity()==null || iEvent.getMinCapacity().equals(iEvent.getMaxCapacity())) { message += "<td>"+iEvent.getMinCapacity()+"</td>"; } else { message += "<td>"+iEvent.getMinCapacity()+" - "+iEvent.getMaxCapacity()+"</td>"; } } if (iEvent.getSponsoringOrganization()!=null) { message += "<tr><td>Sponsoring Organization</td><td>"+iEvent.getSponsoringOrganization().getName()+"</td></tr>"; } if (iEvent.getMainContact()!=null) { message += "<tr><td>Main Contact</td><td>"; message += "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"; if (iEvent.getMainContact().getLastName()!=null) message += iEvent.getMainContact().getLastName(); if (iEvent.getMainContact().getFirstName()!=null) message += ", "+iEvent.getMainContact().getFirstName(); if (iEvent.getMainContact().getMiddleName()!=null && iEvent.getMainContact().getMiddleName().length()>0) message += ", "+iEvent.getMainContact().getMiddleName(); message += "</a></td></tr>"; } if (!iMeetings.isEmpty()) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>"; switch (iAction) { case sActionCreate : - message += "Following meetings were requested by you or on your behalf confirmation will follow"; + message += "Following meetings were requested by you or on your behalf, confirmation will follow"; break; case sActionApprove : message += "Following meetings were approved"; break; case sActionReject : message += "Following meetings were rejected"; if (iNote!=null && iNote.length()>0) message += " (see the note below for more details)"; break; case sActionAddMeeting : - message += "Following meetings were added by you or on your behalf confirmation will follow"; + message += "Following meetings were added by you or on your behalf, confirmation will follow"; break; case sActionDelete : message += "Following meetings were deleted by you or on your behalf"; break; } message += "</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td></tr>"; for (MultiMeeting m : iMeetings) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td></tr>"; } message += "</table></td></tr>"; } if (iNote!=null && iNote.length()>0) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>Notes</font>"; message += "</td></tr><tr><td colspan='2' >"; message += iNote.replaceAll("\n", "<br>"); message += "</td></tr>"; } if (iAction!=sActionCreate) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Meetings of "+iEvent.getEventName()+"</font>"; message += "</td></tr>"; if (iEvent.getMeetings().isEmpty()) { message += "<tr><td colspan='2' style='background-color:';>"; message += "No meeting left, the event "+iEvent.getEventName()+" was deleted as well."; message += "</td></tr>"; } else { message += "<tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td><td><i>Capacity</i></td><td><i>Approved</i></td></tr>"; for (MultiMeeting m : iEvent.getMultiMeetings()) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getCapacity()); message += "</td><td>"; if (m.isPast()) { message += ""; } else if (m.getMeetings().first().getApprovedDate()==null) { message += "<i>Waiting Approval</i>"; } else { message += new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getApprovedDate()); } message += "</td></tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Notes of "+iEvent.getEventName()+"</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%' cellspacing='0' cellpadding='3'>"; message += "<tr><td><i>Date</i></td><td><i>Action</i></td><td><i>Meetings</i></td><td><i>Note</i></td></tr>"; for (EventNote note : new TreeSet<EventNote>(iEvent.getNotes())) { message += "<tr style=\"background-color:"+EventNote.sEventNoteTypeBgColor[note.getNoteType()]+";\" valign='top'>"; message += "<td>"+new SimpleDateFormat("MM/dd hh:mmaa").format(note.getTimeStamp())+"</td>"; message += "<td>"+EventNote.sEventNoteTypeName[note.getNoteType()]+"</td>"; message += "<td>"+note.getMeetingsHtml()+"</td>"; message += "<td>"+(note.getTextNote()==null?"":note.getTextNote().replaceAll("\n", "<br>"))+"</td>"; message += "</tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2'>&nbsp;</td></tr>"; message += "<tr><td colspan='2' style='border-top: 1px #2020FF solid;' align='center'>"; message += "This email was automatically generated at "; message += request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); message += ",<br>by UniTime "+Constants.VERSION+"."+Constants.BLD_NUMBER.replaceAll("@build.number@", "?"); message += " (Univesity Timetabling Application, http://www.unitime.org)."; message += "</td></tr></table>"; Properties p = ApplicationProperties.getProperties(); if (p.getProperty("mail.smtp.host")==null && p.getProperty("tmtbl.smtp.host")!=null) p.setProperty("mail.smtp.host", p.getProperty("tmtbl.smtp.host")); Authenticator a = null; if (ApplicationProperties.getProperty("tmtbl.mail.user")!=null && ApplicationProperties.getProperty("tmtbl.mail.pwd")!=null) { p.setProperty("mail.smtp.user", ApplicationProperties.getProperty("tmtbl.mail.user")); p.setProperty("mail.smtp.auth", "true"); a = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( ApplicationProperties.getProperty("tmtbl.mail.user"), ApplicationProperties.getProperty("tmtbl.mail.pwd")); } }; } javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(p, a); MimeMessage mail = new MimeMessage(mailSession); mail.setSubject(subject); InternetAddress from = new InternetAddress( ApplicationProperties.getProperty("tmtbl.inquiry.sender",ApplicationProperties.getProperty("tmtbl.contact.email")), ApplicationProperties.getProperty("tmtbl.inquiry.sender.name")); mail.setFrom(from); MimeBodyPart text = new MimeBodyPart(); text.setContent(message, "text/html"); Multipart body = new MimeMultipart(); body.addBodyPart(text); conf = ApplicationProperties.getTempFile("email", "html"); PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(conf)); pw.println(message); pw.flush(); pw.close(); pw=null; } catch (Exception e) {} finally { if (pw!=null) pw.close(); } String to = ""; if (iEvent.getMainContact()!=null && iEvent.getMainContact().getEmailAddress()!=null) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getMainContact().getEmailAddress(),iEvent.getMainContact().getName())); to = "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"+iEvent.getMainContact().getShortName()+"</a>"; } if (iEvent.getEmail()!=null && iEvent.getEmail().length()>0) { for (StringTokenizer stk = new StringTokenizer(iEvent.getEmail(),";:,\n\r\t");stk.hasMoreTokens();) { String email = stk.nextToken(); mail.addRecipient(RecipientType.CC, new InternetAddress(email)); if (to.length()>0) to+=", "; to += email; } } if (iEvent.getSponsoringOrganization()!=null && iEvent.getSponsoringOrganization().getEmail()!=null && iEvent.getSponsoringOrganization().getEmail().length()>0) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getSponsoringOrganization().getEmail(),iEvent.getSponsoringOrganization().getName())); if (to.length()>0) to+=", "; to += "<a href='mailto:"+iEvent.getSponsoringOrganization().getEmail()+"'>"+iEvent.getSponsoringOrganization().getName()+"</a>"; } mail.setSentDate(new Date()); mail.setContent(body); Transport.send(mail); request.getSession().setAttribute(Constants.REQUEST_MSSG, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ subject+" Confirmation email sent to "+to+"."+ (conf==null || !conf.exists()?"":"</a>")); } catch (Exception e) { sLog.error(e.getMessage(),e); request.getSession().setAttribute(Constants.REQUEST_WARN, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ (subject==null?"":subject+" ")+"Unable to send confirmation email, reason: "+e.getMessage()+ (conf==null || !conf.exists()?"":"</a>")); } } }
false
true
public void send(HttpServletRequest request) { String subject = null; File conf = null; try { User user = Web.getUser(request.getSession()); if (Roles.ADMIN_ROLE.equals(user.getRole()) || Roles.EVENT_MGR_ROLE.equals(user.getRole())) { if (iAction!=sActionReject && iAction!=sActionApprove) return; } switch (iAction) { case sActionCreate : subject = "Event "+iEvent.getEventName()+" created."; break; case sActionApprove : subject = "Event "+iEvent.getEventName()+" approved."; break; case sActionReject : subject = "Event "+iEvent.getEventName()+" rejected."; break; case sActionUpdate : subject = "Event "+iEvent.getEventName()+" updated."; break; case sActionAddMeeting : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings added)."; break; case sActionDelete : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings deleted)."; break; } if (!"true".equals(ApplicationProperties.getProperty("tmtbl.event.confirmationEmail","true"))) { request.getSession().setAttribute(Constants.REQUEST_MSSG, "Confirmation emails are disabled."); return; } String message = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; message += "<html><head>"; message += "<title>"+subject+"</title>"; message += "<meta http-equiv='Content-Type' content='text/html; charset=windows-1250'>"; message += "<meta name='Author' content='UniTime LLC'>"; message += "<style type='text/css'>"; message += "<!--" + "A:link { color: blue; text-decoration: none; }" + "A:visited { color: blue; text-decoration: none; }" + "A:active { color: blue; text-decoration: none; }" + "A:hover { color: blue; text-decoration: none; }" + "-->"; message += "</style></head><body bgcolor='#ffffff' style='font-size: 10pt; font-family: arial;'>"; message += "<table border='0' width='95%' align='center' cellspacing='10'>"; message += "<tr><td colspan='2' style='border-bottom: 2px #2020FF solid;'><font size='+2'>"; message += iEvent.getEventName(); message += "</td></tr>"; message += "<tr><td>Event Type</td><td>"+iEvent.getEventTypeLabel()+"</td></tr>"; if (iEvent.getMinCapacity()!=null) { message += "<tr><td>"+(iEvent.getEventType()==Event.sEventTypeSpecial?"Expected Size":"Event Capacity")+":</td>"; if (iEvent.getMaxCapacity()==null || iEvent.getMinCapacity().equals(iEvent.getMaxCapacity())) { message += "<td>"+iEvent.getMinCapacity()+"</td>"; } else { message += "<td>"+iEvent.getMinCapacity()+" - "+iEvent.getMaxCapacity()+"</td>"; } } if (iEvent.getSponsoringOrganization()!=null) { message += "<tr><td>Sponsoring Organization</td><td>"+iEvent.getSponsoringOrganization().getName()+"</td></tr>"; } if (iEvent.getMainContact()!=null) { message += "<tr><td>Main Contact</td><td>"; message += "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"; if (iEvent.getMainContact().getLastName()!=null) message += iEvent.getMainContact().getLastName(); if (iEvent.getMainContact().getFirstName()!=null) message += ", "+iEvent.getMainContact().getFirstName(); if (iEvent.getMainContact().getMiddleName()!=null && iEvent.getMainContact().getMiddleName().length()>0) message += ", "+iEvent.getMainContact().getMiddleName(); message += "</a></td></tr>"; } if (!iMeetings.isEmpty()) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>"; switch (iAction) { case sActionCreate : message += "Following meetings were requested by you or on your behalf confirmation will follow"; break; case sActionApprove : message += "Following meetings were approved"; break; case sActionReject : message += "Following meetings were rejected"; if (iNote!=null && iNote.length()>0) message += " (see the note below for more details)"; break; case sActionAddMeeting : message += "Following meetings were added by you or on your behalf confirmation will follow"; break; case sActionDelete : message += "Following meetings were deleted by you or on your behalf"; break; } message += "</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td></tr>"; for (MultiMeeting m : iMeetings) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td></tr>"; } message += "</table></td></tr>"; } if (iNote!=null && iNote.length()>0) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>Notes</font>"; message += "</td></tr><tr><td colspan='2' >"; message += iNote.replaceAll("\n", "<br>"); message += "</td></tr>"; } if (iAction!=sActionCreate) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Meetings of "+iEvent.getEventName()+"</font>"; message += "</td></tr>"; if (iEvent.getMeetings().isEmpty()) { message += "<tr><td colspan='2' style='background-color:';>"; message += "No meeting left, the event "+iEvent.getEventName()+" was deleted as well."; message += "</td></tr>"; } else { message += "<tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td><td><i>Capacity</i></td><td><i>Approved</i></td></tr>"; for (MultiMeeting m : iEvent.getMultiMeetings()) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getCapacity()); message += "</td><td>"; if (m.isPast()) { message += ""; } else if (m.getMeetings().first().getApprovedDate()==null) { message += "<i>Waiting Approval</i>"; } else { message += new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getApprovedDate()); } message += "</td></tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Notes of "+iEvent.getEventName()+"</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%' cellspacing='0' cellpadding='3'>"; message += "<tr><td><i>Date</i></td><td><i>Action</i></td><td><i>Meetings</i></td><td><i>Note</i></td></tr>"; for (EventNote note : new TreeSet<EventNote>(iEvent.getNotes())) { message += "<tr style=\"background-color:"+EventNote.sEventNoteTypeBgColor[note.getNoteType()]+";\" valign='top'>"; message += "<td>"+new SimpleDateFormat("MM/dd hh:mmaa").format(note.getTimeStamp())+"</td>"; message += "<td>"+EventNote.sEventNoteTypeName[note.getNoteType()]+"</td>"; message += "<td>"+note.getMeetingsHtml()+"</td>"; message += "<td>"+(note.getTextNote()==null?"":note.getTextNote().replaceAll("\n", "<br>"))+"</td>"; message += "</tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2'>&nbsp;</td></tr>"; message += "<tr><td colspan='2' style='border-top: 1px #2020FF solid;' align='center'>"; message += "This email was automatically generated at "; message += request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); message += ",<br>by UniTime "+Constants.VERSION+"."+Constants.BLD_NUMBER.replaceAll("@build.number@", "?"); message += " (Univesity Timetabling Application, http://www.unitime.org)."; message += "</td></tr></table>"; Properties p = ApplicationProperties.getProperties(); if (p.getProperty("mail.smtp.host")==null && p.getProperty("tmtbl.smtp.host")!=null) p.setProperty("mail.smtp.host", p.getProperty("tmtbl.smtp.host")); Authenticator a = null; if (ApplicationProperties.getProperty("tmtbl.mail.user")!=null && ApplicationProperties.getProperty("tmtbl.mail.pwd")!=null) { p.setProperty("mail.smtp.user", ApplicationProperties.getProperty("tmtbl.mail.user")); p.setProperty("mail.smtp.auth", "true"); a = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( ApplicationProperties.getProperty("tmtbl.mail.user"), ApplicationProperties.getProperty("tmtbl.mail.pwd")); } }; } javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(p, a); MimeMessage mail = new MimeMessage(mailSession); mail.setSubject(subject); InternetAddress from = new InternetAddress( ApplicationProperties.getProperty("tmtbl.inquiry.sender",ApplicationProperties.getProperty("tmtbl.contact.email")), ApplicationProperties.getProperty("tmtbl.inquiry.sender.name")); mail.setFrom(from); MimeBodyPart text = new MimeBodyPart(); text.setContent(message, "text/html"); Multipart body = new MimeMultipart(); body.addBodyPart(text); conf = ApplicationProperties.getTempFile("email", "html"); PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(conf)); pw.println(message); pw.flush(); pw.close(); pw=null; } catch (Exception e) {} finally { if (pw!=null) pw.close(); } String to = ""; if (iEvent.getMainContact()!=null && iEvent.getMainContact().getEmailAddress()!=null) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getMainContact().getEmailAddress(),iEvent.getMainContact().getName())); to = "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"+iEvent.getMainContact().getShortName()+"</a>"; } if (iEvent.getEmail()!=null && iEvent.getEmail().length()>0) { for (StringTokenizer stk = new StringTokenizer(iEvent.getEmail(),";:,\n\r\t");stk.hasMoreTokens();) { String email = stk.nextToken(); mail.addRecipient(RecipientType.CC, new InternetAddress(email)); if (to.length()>0) to+=", "; to += email; } } if (iEvent.getSponsoringOrganization()!=null && iEvent.getSponsoringOrganization().getEmail()!=null && iEvent.getSponsoringOrganization().getEmail().length()>0) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getSponsoringOrganization().getEmail(),iEvent.getSponsoringOrganization().getName())); if (to.length()>0) to+=", "; to += "<a href='mailto:"+iEvent.getSponsoringOrganization().getEmail()+"'>"+iEvent.getSponsoringOrganization().getName()+"</a>"; } mail.setSentDate(new Date()); mail.setContent(body); Transport.send(mail); request.getSession().setAttribute(Constants.REQUEST_MSSG, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ subject+" Confirmation email sent to "+to+"."+ (conf==null || !conf.exists()?"":"</a>")); } catch (Exception e) { sLog.error(e.getMessage(),e); request.getSession().setAttribute(Constants.REQUEST_WARN, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ (subject==null?"":subject+" ")+"Unable to send confirmation email, reason: "+e.getMessage()+ (conf==null || !conf.exists()?"":"</a>")); } }
public void send(HttpServletRequest request) { String subject = null; File conf = null; try { User user = Web.getUser(request.getSession()); if (Roles.ADMIN_ROLE.equals(user.getRole()) || Roles.EVENT_MGR_ROLE.equals(user.getRole())) { if (iAction!=sActionReject && iAction!=sActionApprove) return; } switch (iAction) { case sActionCreate : subject = "Event "+iEvent.getEventName()+" created."; break; case sActionApprove : subject = "Event "+iEvent.getEventName()+" approved."; break; case sActionReject : subject = "Event "+iEvent.getEventName()+" rejected."; break; case sActionUpdate : subject = "Event "+iEvent.getEventName()+" updated."; break; case sActionAddMeeting : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings added)."; break; case sActionDelete : subject = "Event "+iEvent.getEventName()+" updated (one or more meetings deleted)."; break; } if (!"true".equals(ApplicationProperties.getProperty("tmtbl.event.confirmationEmail","true"))) { request.getSession().setAttribute(Constants.REQUEST_MSSG, "Confirmation emails are disabled."); return; } String message = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; message += "<html><head>"; message += "<title>"+subject+"</title>"; message += "<meta http-equiv='Content-Type' content='text/html; charset=windows-1250'>"; message += "<meta name='Author' content='UniTime LLC'>"; message += "<style type='text/css'>"; message += "<!--" + "A:link { color: blue; text-decoration: none; }" + "A:visited { color: blue; text-decoration: none; }" + "A:active { color: blue; text-decoration: none; }" + "A:hover { color: blue; text-decoration: none; }" + "-->"; message += "</style></head><body bgcolor='#ffffff' style='font-size: 10pt; font-family: arial;'>"; message += "<table border='0' width='95%' align='center' cellspacing='10'>"; message += "<tr><td colspan='2' style='border-bottom: 2px #2020FF solid;'><font size='+2'>"; message += iEvent.getEventName(); message += "</td></tr>"; message += "<tr><td>Event Type</td><td>"+iEvent.getEventTypeLabel()+"</td></tr>"; if (iEvent.getMinCapacity()!=null) { message += "<tr><td>"+(iEvent.getEventType()==Event.sEventTypeSpecial?"Expected Size":"Event Capacity")+":</td>"; if (iEvent.getMaxCapacity()==null || iEvent.getMinCapacity().equals(iEvent.getMaxCapacity())) { message += "<td>"+iEvent.getMinCapacity()+"</td>"; } else { message += "<td>"+iEvent.getMinCapacity()+" - "+iEvent.getMaxCapacity()+"</td>"; } } if (iEvent.getSponsoringOrganization()!=null) { message += "<tr><td>Sponsoring Organization</td><td>"+iEvent.getSponsoringOrganization().getName()+"</td></tr>"; } if (iEvent.getMainContact()!=null) { message += "<tr><td>Main Contact</td><td>"; message += "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"; if (iEvent.getMainContact().getLastName()!=null) message += iEvent.getMainContact().getLastName(); if (iEvent.getMainContact().getFirstName()!=null) message += ", "+iEvent.getMainContact().getFirstName(); if (iEvent.getMainContact().getMiddleName()!=null && iEvent.getMainContact().getMiddleName().length()>0) message += ", "+iEvent.getMainContact().getMiddleName(); message += "</a></td></tr>"; } if (!iMeetings.isEmpty()) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>"; switch (iAction) { case sActionCreate : message += "Following meetings were requested by you or on your behalf, confirmation will follow"; break; case sActionApprove : message += "Following meetings were approved"; break; case sActionReject : message += "Following meetings were rejected"; if (iNote!=null && iNote.length()>0) message += " (see the note below for more details)"; break; case sActionAddMeeting : message += "Following meetings were added by you or on your behalf, confirmation will follow"; break; case sActionDelete : message += "Following meetings were deleted by you or on your behalf"; break; } message += "</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td></tr>"; for (MultiMeeting m : iMeetings) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td></tr>"; } message += "</table></td></tr>"; } if (iNote!=null && iNote.length()>0) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>Notes</font>"; message += "</td></tr><tr><td colspan='2' >"; message += iNote.replaceAll("\n", "<br>"); message += "</td></tr>"; } if (iAction!=sActionCreate) { message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Meetings of "+iEvent.getEventName()+"</font>"; message += "</td></tr>"; if (iEvent.getMeetings().isEmpty()) { message += "<tr><td colspan='2' style='background-color:';>"; message += "No meeting left, the event "+iEvent.getEventName()+" was deleted as well."; message += "</td></tr>"; } else { message += "<tr><td colspan='2'>"; message += "<table border='0' width='100%'>"; message += "<tr><td><i>Date</i></td><td><i>Time</i></td><td><i>Location</i></td><td><i>Capacity</i></td><td><i>Approved</i></td></tr>"; for (MultiMeeting m : iEvent.getMultiMeetings()) { message += "<tr><td>"; message += m.getDays()+" "+new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getMeetingDate()); message += (m.getMeetings().size()>1?" - "+new SimpleDateFormat("MM/dd").format(m.getMeetings().last().getMeetingDate()):""); message += "</td><td>"; message += m.getMeetings().first().startTime()+" - "+m.getMeetings().first().stopTime(); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getLabel()); message += "</td><td>"; message += (m.getMeetings().first().getLocation()==null?"":" "+m.getMeetings().first().getLocation().getCapacity()); message += "</td><td>"; if (m.isPast()) { message += ""; } else if (m.getMeetings().first().getApprovedDate()==null) { message += "<i>Waiting Approval</i>"; } else { message += new SimpleDateFormat("MM/dd").format(m.getMeetings().first().getApprovedDate()); } message += "</td></tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2' style='border-bottom: 1px #2020FF solid; font-variant:small-caps;'>"; message += "<br><font size='+1'>All Notes of "+iEvent.getEventName()+"</font>"; message += "</td></tr><tr><td colspan='2'>"; message += "<table border='0' width='100%' cellspacing='0' cellpadding='3'>"; message += "<tr><td><i>Date</i></td><td><i>Action</i></td><td><i>Meetings</i></td><td><i>Note</i></td></tr>"; for (EventNote note : new TreeSet<EventNote>(iEvent.getNotes())) { message += "<tr style=\"background-color:"+EventNote.sEventNoteTypeBgColor[note.getNoteType()]+";\" valign='top'>"; message += "<td>"+new SimpleDateFormat("MM/dd hh:mmaa").format(note.getTimeStamp())+"</td>"; message += "<td>"+EventNote.sEventNoteTypeName[note.getNoteType()]+"</td>"; message += "<td>"+note.getMeetingsHtml()+"</td>"; message += "<td>"+(note.getTextNote()==null?"":note.getTextNote().replaceAll("\n", "<br>"))+"</td>"; message += "</tr>"; } message += "</table></td></tr>"; } message += "<tr><td colspan='2'>&nbsp;</td></tr>"; message += "<tr><td colspan='2' style='border-top: 1px #2020FF solid;' align='center'>"; message += "This email was automatically generated at "; message += request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); message += ",<br>by UniTime "+Constants.VERSION+"."+Constants.BLD_NUMBER.replaceAll("@build.number@", "?"); message += " (Univesity Timetabling Application, http://www.unitime.org)."; message += "</td></tr></table>"; Properties p = ApplicationProperties.getProperties(); if (p.getProperty("mail.smtp.host")==null && p.getProperty("tmtbl.smtp.host")!=null) p.setProperty("mail.smtp.host", p.getProperty("tmtbl.smtp.host")); Authenticator a = null; if (ApplicationProperties.getProperty("tmtbl.mail.user")!=null && ApplicationProperties.getProperty("tmtbl.mail.pwd")!=null) { p.setProperty("mail.smtp.user", ApplicationProperties.getProperty("tmtbl.mail.user")); p.setProperty("mail.smtp.auth", "true"); a = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( ApplicationProperties.getProperty("tmtbl.mail.user"), ApplicationProperties.getProperty("tmtbl.mail.pwd")); } }; } javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(p, a); MimeMessage mail = new MimeMessage(mailSession); mail.setSubject(subject); InternetAddress from = new InternetAddress( ApplicationProperties.getProperty("tmtbl.inquiry.sender",ApplicationProperties.getProperty("tmtbl.contact.email")), ApplicationProperties.getProperty("tmtbl.inquiry.sender.name")); mail.setFrom(from); MimeBodyPart text = new MimeBodyPart(); text.setContent(message, "text/html"); Multipart body = new MimeMultipart(); body.addBodyPart(text); conf = ApplicationProperties.getTempFile("email", "html"); PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(conf)); pw.println(message); pw.flush(); pw.close(); pw=null; } catch (Exception e) {} finally { if (pw!=null) pw.close(); } String to = ""; if (iEvent.getMainContact()!=null && iEvent.getMainContact().getEmailAddress()!=null) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getMainContact().getEmailAddress(),iEvent.getMainContact().getName())); to = "<a href='mailto:"+iEvent.getMainContact().getEmailAddress()+"'>"+iEvent.getMainContact().getShortName()+"</a>"; } if (iEvent.getEmail()!=null && iEvent.getEmail().length()>0) { for (StringTokenizer stk = new StringTokenizer(iEvent.getEmail(),";:,\n\r\t");stk.hasMoreTokens();) { String email = stk.nextToken(); mail.addRecipient(RecipientType.CC, new InternetAddress(email)); if (to.length()>0) to+=", "; to += email; } } if (iEvent.getSponsoringOrganization()!=null && iEvent.getSponsoringOrganization().getEmail()!=null && iEvent.getSponsoringOrganization().getEmail().length()>0) { mail.addRecipient(RecipientType.TO, new InternetAddress(iEvent.getSponsoringOrganization().getEmail(),iEvent.getSponsoringOrganization().getName())); if (to.length()>0) to+=", "; to += "<a href='mailto:"+iEvent.getSponsoringOrganization().getEmail()+"'>"+iEvent.getSponsoringOrganization().getName()+"</a>"; } mail.setSentDate(new Date()); mail.setContent(body); Transport.send(mail); request.getSession().setAttribute(Constants.REQUEST_MSSG, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ subject+" Confirmation email sent to "+to+"."+ (conf==null || !conf.exists()?"":"</a>")); } catch (Exception e) { sLog.error(e.getMessage(),e); request.getSession().setAttribute(Constants.REQUEST_WARN, (conf==null || !conf.exists()?"":"<a class='noFancyLinks' href='temp/"+conf.getName()+"'>")+ (subject==null?"":subject+" ")+"Unable to send confirmation email, reason: "+e.getMessage()+ (conf==null || !conf.exists()?"":"</a>")); } }
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/callgraph/core/SystemTapParser.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/callgraph/core/SystemTapParser.java index 512980267..3039d7465 100644 --- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/callgraph/core/SystemTapParser.java +++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/callgraph/core/SystemTapParser.java @@ -1,408 +1,408 @@ /******************************************************************************* * Copyright (c) 2009 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat - initial API and implementation *******************************************************************************/ package org.eclipse.linuxtools.callgraph.core; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; public abstract class SystemTapParser extends Job { protected IProgressMonitor monitor; protected String sourcePath; protected String viewID; protected SystemTapView view; protected boolean realTime = false; protected Object data; protected Object internalData; private String secondaryID = ""; //$NON-NLS-1$ public boolean isDone; private RunTimeJob job; private boolean jobCancelled; public SystemTapParser() { super("Parsing data"); //$NON-NLS-1$ this.sourcePath = PluginConstants.getDefaultIOPath(); this.viewID = null; initialize(); isDone = false; //PURELY FOR TESTING if (monitor == null){ monitor = new NullProgressMonitor(); } } public SystemTapParser(String name, String filePath) { super(name); // BY DEFAULT READ/WRITE FROM HERE if (filePath != null) this.sourcePath = filePath; else this.sourcePath = PluginConstants.getDefaultIOPath(); this.viewID = null; initialize(); } /** * Initialize will be called in the constructors for this class. Use this * method to initialize variables. */ protected abstract void initialize(); /** * Implement this method to execute parsing. The return from * executeParsing() will be the return value of the run command. * * SystemTapParser will call executeParsing() within its run method. (i.e. * will execute in a separate, non-UI thread) * * @return */ public abstract IStatus nonRealTimeParsing(); /** * Implement this method if your parser is to execute in realtime. This method * will be called as part of a while loop in a separate Job. Use the setInternalData * method to initialize some data object for use in realTimeParsing. The default * setInternalMethod method will set internalData to a BufferedReader * <br> <br> * After the isDone flag is set to true, the realTimeParsing() method will * be run one more time to catch any stragglers. */ public abstract IStatus realTimeParsing(); /** * Cleans names of form 'name").return', returning just the name * * @param name */ protected String cleanFunctionName(String name) { return name.split("\"")[0]; //$NON-NLS-1$ } /** * Checks for quotations and brackets in the function name * * @param name */ protected boolean isFunctionNameClean(String name) { if (name.contains("\"") || name.contains(")")) //$NON-NLS-1$ //$NON-NLS-2$ return false; return true; } /** * Creates a popup error dialog in a separate UI thread. Dialog title is * 'Unexpected symbol,' name is 'ParseError' and body is the specified * message. * * @param message */ protected void parsingError(String message) { SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages( Messages.getString("SystemTapParser.ParseErr"), //$NON-NLS-1$ Messages.getString("SystemTapParser.ErrSymbol"), //$NON-NLS-1$ message); mess.schedule(); } /** * Load the specified viewID by creating a StapUIJob. Does not return until the StapUIJob has. * Returns true if the makeView was successful, false otherwise. */ protected boolean makeView() { // Create a UIJob to handle the rest if (viewID != null && viewID.length() > 0) { try { StapUIJob uijob = new StapUIJob(Messages .getString("StapGraphParser.JobName"), this, viewID); //$NON-NLS-1$ uijob.schedule(); uijob.join(); view = uijob.getViewer(); return true; } catch (InterruptedException e) { e.printStackTrace(); } } return false; } @Override protected IStatus run(IProgressMonitor monitor) { // Generate real-time job IStatus returnStatus = Status.CANCEL_STATUS; this.monitor = monitor; if (this.monitor == null) { this.monitor = new NullProgressMonitor(); } - makeView(); if (realTime && (job == null || job.getResult()==null)) { job = new RunTimeJob("RealTimeParser"); //$NON-NLS-1$ job.schedule(); } else { returnStatus = nonRealTimeParsing(); } + makeView(); if (!returnStatus.isOK()){ return returnStatus; } setData(this); return returnStatus; } public void printArrayListMap(HashMap<Integer, ArrayList<Integer>> blah) { int amt = 0; for (int a : blah.keySet()) { amt++; MP.print(a + " ::> "); //$NON-NLS-1$ for (int c : blah.get(a)) { System.out.print(c + " "); //$NON-NLS-1$ } MP.println(""); //$NON-NLS-1$ } } @SuppressWarnings("unchecked") public void printMap(Map blah) { int amt = 0; for (Object a : blah.keySet()) { amt++; MP.println(a + " ::> " + blah.get(a)); //$NON-NLS-1$ } } /** * For easier JUnit testing only. Allows public access to run method without * scheduling an extra job. * * @param m * @return */ public IStatus testRun(IProgressMonitor m, boolean realTime) { try { internalData = new BufferedReader(new FileReader(new File(sourcePath))); if (realTime) return realTimeParsing(); else return nonRealTimeParsing(); } catch (FileNotFoundException e) { e.printStackTrace(); } return Status.CANCEL_STATUS; } public void launchFileErrorDialog() { SystemTapUIErrorMessages err = new SystemTapUIErrorMessages(Messages .getString("SystemTapParser.InvalidFile"), //$NON-NLS-1$ Messages.getString("SystemTapParser.InvalidFile"), //$NON-NLS-1$ Messages.getString("SystemTapParser.InvalidFileMsg1") + sourcePath + //$NON-NLS-1$ Messages.getString("SystemTapParser.InvalidFileMsg2")); //$NON-NLS-1$ err.schedule(); } private class RunTimeJob extends Job { public RunTimeJob(String name) { super(name); } @Override public IStatus run(IProgressMonitor monitor) { IStatus returnStatus = Status.CANCEL_STATUS; try { setInternalData(); while (!isDone){ returnStatus = realTimeParsing(); if (monitor.isCanceled() || returnStatus == Status.CANCEL_STATUS) return Status.CANCEL_STATUS; } returnStatus = realTimeParsing(); } catch (Exception e) { e.printStackTrace(); } return returnStatus; } } /** * Return the Data object. * @return */ public Object getData() { return data; } /** * Generic method for setting the internalData object. This will be called * by a real-time-parser immediately before its main polling loop. By default, * this method will attempt to create a bufferedReader around File(filePath) * * @throws Exception */ protected void setInternalData() throws Exception { File file = new File(sourcePath); internalData = new BufferedReader(new FileReader(file)); } /** * Returns the monitor * * @return */ public IProgressMonitor getMonitor() { return monitor; } /** * Gets the file to read from * * @return */ public String getFile() { return sourcePath; } /** * Sets the file to read from * * @param source */ public void setSourcePath(String source) { this.sourcePath = source; } /** * Slightly more graceful termination than cancelJob. * Setting to true will cause the parser's RunTimeJob to terminate at the end * of its current iteration. Does not offer as solid a guarantee * of termination, however. * @param val */ public void setDone(boolean val) { isDone = val; } public void setMonitor(IProgressMonitor m) { this.monitor = m; } /** * Set whether or not this parser runs in real time. If viewID has already * been set, this will also attempt to open the view. * * @throws InterruptedException */ public void setRealTime(boolean val) throws InterruptedException { realTime = val; } /** * Set the viewID to use for this parser -- see the callgraph.core view * extension point. If realTime is set to true, this will also attempt to * open the view. * * @throws InterruptedException */ public void setViewID(String value) throws InterruptedException { viewID = value; } /** * Called at the end of a non-realtime run. * Feel free to override this method if using non-realtime functions. * The setData method will be called after executeParsing() is run. The getData() method * will be used by the SystemTapView to get the data associated with this parser. * <br><br> * Alternatively, you can cast the parser within SystemTapView to your own parser class and access * its data structures that way. */ public void setData(Object obj) { data = obj; } /** * Cancels the RunTimeJob affiliated with this parser. Returns the result * of job.cancel() if job is not null, or false if job is null. */ public boolean cancelJob() { if (job != null) { jobCancelled = true; return job.cancel(); } return false; } /** * Returns true if job is not null and the job's last result was CANCEL_STATUS. * False otherwise. */ public boolean isJobCancelled() { if ((job != null && job.getResult() == Status.CANCEL_STATUS) || jobCancelled) { return true; } return false; } public void setKillButtonEnabled(boolean val) { if (view != null) view.setKillButtonEnabled(val); } public boolean isRealTime() { return realTime; } public void setSecondaryID(String secondaryID) { this.secondaryID = secondaryID; } public String getSecondaryID() { return secondaryID; } }
false
true
protected IStatus run(IProgressMonitor monitor) { // Generate real-time job IStatus returnStatus = Status.CANCEL_STATUS; this.monitor = monitor; if (this.monitor == null) { this.monitor = new NullProgressMonitor(); } makeView(); if (realTime && (job == null || job.getResult()==null)) { job = new RunTimeJob("RealTimeParser"); //$NON-NLS-1$ job.schedule(); } else { returnStatus = nonRealTimeParsing(); } if (!returnStatus.isOK()){ return returnStatus; } setData(this); return returnStatus; }
protected IStatus run(IProgressMonitor monitor) { // Generate real-time job IStatus returnStatus = Status.CANCEL_STATUS; this.monitor = monitor; if (this.monitor == null) { this.monitor = new NullProgressMonitor(); } if (realTime && (job == null || job.getResult()==null)) { job = new RunTimeJob("RealTimeParser"); //$NON-NLS-1$ job.schedule(); } else { returnStatus = nonRealTimeParsing(); } makeView(); if (!returnStatus.isOK()){ return returnStatus; } setData(this); return returnStatus; }
diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineSizzleIE.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineSizzleIE.java index 4c4755b0..9aad4204 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineSizzleIE.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineSizzleIE.java @@ -1,956 +1,956 @@ /* * Copyright 2011, The gwtquery team. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.query.client.impl; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; /** * Original Sizzle CSS Selector Engine v1.0 inserted in a JSNI method. * There are a couple of differences with the original: * - It uses the window.IES instead of window.Sizzle to avoid interfering. * - All the stuff related with non IE browsers has been removed making this * implementation a bit faster and smaller. * * There are some reasons why we are using sizzle with IE instead of any other * implementation. * - Sizzle is the faster selector with IE we have tested. * - Only IE8 under some conditions and with a limited set of selectors * has a native and fast method for selecting dom elements. So we need * a complete implementation in javascript. * - We don't want to make the effort of writing a complete js implementation (DRY). * - It is supposed this class will be here for a while, because new versions of * IE are coming. */ public class SelectorEngineSizzleIE extends SelectorEngineImpl { public static native void initialize() /*-{ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false; var IES = function(selector, context, results, seed) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = IES.isXML(context), soFar = selector, ret, cur, pop, i; // Reset the position of the chunker regexp (start from head) do { chunker.exec(""); m = chunker.exec(soFar); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : IES( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = IES.find( parts.shift(), context, contextXML ); context = ret.expr ? IES.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : IES.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? IES.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { - cur = ""; + cur = "-"; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { IES.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && IES.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { IES( extra, origContext, results, seed ); IES.uniqueSort( results ); } return results; }; IES.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = false; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; IES.matches = function(expr, set){ return IES(expr, null, null, set); }; IES.find = function(expr, context, isXML){ var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; IES.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && IES.isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { IES.error( expr ); } else { break; } } old = expr; } return curLoop; }; IES.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = IES.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href", 2); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { IES.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string", elem, i = 0, l = checkSet.length; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { IES.filter( part, checkSet, true ); } } }, "-": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, // IE espedific TAG: function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = IES(match[3], null, null, curLoop); } else { var ret = IES.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!IES( match[3], elem ).length; }, header: function(elem){ return (/h\d/i).test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return (/input|select|textarea|button/i).test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || IES.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { IES.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || [], i = 0; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; // Utility function for retreiving the text value of an array of DOM nodes IES.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += IES.getText( elem.childNodes ); } } return ret; }; function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( IES.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } IES.contains = function(a, b) { return a !== b && (a.contains ? a.contains(b) : true); }; IES.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { IES( selector, root[i], tmpSet ); } return IES.filter( later, tmpSet ); }; // EXPOSE window.IES = IES; $wnd.IES = IES; })(); }-*/; private static native JsArray<Element> select(String selector, Node context, JsArray<Element> results, JsArray<Element> seed) /*-{ return $wnd.IES(selector, context, results, seed); }-*/; static boolean initialized = false; public SelectorEngineSizzleIE() { if (!initialized) { initialize(); } } public NodeList<Element> select(String selector, Node context) { JsArray<Element> results = JavaScriptObject.createArray().cast(); return select(selector, context, results, null).cast(); } }
true
true
public static native void initialize() /*-{ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false; var IES = function(selector, context, results, seed) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = IES.isXML(context), soFar = selector, ret, cur, pop, i; // Reset the position of the chunker regexp (start from head) do { chunker.exec(""); m = chunker.exec(soFar); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : IES( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = IES.find( parts.shift(), context, contextXML ); context = ret.expr ? IES.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : IES.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? IES.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { IES.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && IES.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { IES( extra, origContext, results, seed ); IES.uniqueSort( results ); } return results; }; IES.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = false; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; IES.matches = function(expr, set){ return IES(expr, null, null, set); }; IES.find = function(expr, context, isXML){ var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; IES.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && IES.isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { IES.error( expr ); } else { break; } } old = expr; } return curLoop; }; IES.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = IES.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href", 2); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { IES.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string", elem, i = 0, l = checkSet.length; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { IES.filter( part, checkSet, true ); } } }, "-": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, // IE espedific TAG: function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = IES(match[3], null, null, curLoop); } else { var ret = IES.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!IES( match[3], elem ).length; }, header: function(elem){ return (/h\d/i).test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return (/input|select|textarea|button/i).test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || IES.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { IES.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || [], i = 0; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; // Utility function for retreiving the text value of an array of DOM nodes IES.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += IES.getText( elem.childNodes ); } } return ret; }; function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( IES.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } IES.contains = function(a, b) { return a !== b && (a.contains ? a.contains(b) : true); }; IES.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { IES( selector, root[i], tmpSet ); } return IES.filter( later, tmpSet ); }; // EXPOSE window.IES = IES; $wnd.IES = IES; })(); }-*/;
public static native void initialize() /*-{ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false; var IES = function(selector, context, results, seed) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = IES.isXML(context), soFar = selector, ret, cur, pop, i; // Reset the position of the chunker regexp (start from head) do { chunker.exec(""); m = chunker.exec(soFar); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : IES( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = IES.find( parts.shift(), context, contextXML ); context = ret.expr ? IES.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : IES.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? IES.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = "-"; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { IES.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && IES.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { IES( extra, origContext, results, seed ); IES.uniqueSort( results ); } return results; }; IES.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = false; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; IES.matches = function(expr, set){ return IES(expr, null, null, set); }; IES.find = function(expr, context, isXML){ var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; IES.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && IES.isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { IES.error( expr ); } else { break; } } old = expr; } return curLoop; }; IES.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = IES.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href", 2); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { IES.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string", elem, i = 0, l = checkSet.length; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { IES.filter( part, checkSet, true ); } } }, "-": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck, nodeCheck; if ( typeof part === "string" && !/\W/.test(part) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, // IE espedific TAG: function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = IES(match[3], null, null, curLoop); } else { var ret = IES.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!IES( match[3], elem ).length; }, header: function(elem){ return (/h\d/i).test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return (/input|select|textarea|button/i).test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || IES.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { IES.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || [], i = 0; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; // Utility function for retreiving the text value of an array of DOM nodes IES.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += IES.getText( elem.childNodes ); } } return ret; }; function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( IES.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } IES.contains = function(a, b) { return a !== b && (a.contains ? a.contains(b) : true); }; IES.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { IES( selector, root[i], tmpSet ); } return IES.filter( later, tmpSet ); }; // EXPOSE window.IES = IES; $wnd.IES = IES; })(); }-*/;
diff --git a/src/org/rascalmpl/library/vis/figure/combine/WithInnerFig.java b/src/org/rascalmpl/library/vis/figure/combine/WithInnerFig.java index a06bf145c7..e160f0fc78 100644 --- a/src/org/rascalmpl/library/vis/figure/combine/WithInnerFig.java +++ b/src/org/rascalmpl/library/vis/figure/combine/WithInnerFig.java @@ -1,69 +1,69 @@ package org.rascalmpl.library.vis.figure.combine; import static org.rascalmpl.library.vis.properties.TwoDProperties.ALIGN; import static org.rascalmpl.library.vis.properties.TwoDProperties.GAP; import static org.rascalmpl.library.vis.properties.TwoDProperties.GROW; import static org.rascalmpl.library.vis.properties.TwoDProperties.SHRINK; import static org.rascalmpl.library.vis.util.vector.Dimension.HOR_VER; import org.rascalmpl.library.vis.figure.Figure; import org.rascalmpl.library.vis.properties.PropertyManager; import org.rascalmpl.library.vis.util.vector.Dimension; import org.rascalmpl.library.vis.util.vector.Rectangle; public abstract class WithInnerFig extends Figure { final static boolean debug = false; public static final Figure[] EMPTY_ARRAY = new Figure[0]; public Figure innerFig; public WithInnerFig(Figure inner, PropertyManager properties) { super(properties); this.innerFig = inner; setInnerFig(inner); } protected void setInnerFig(Figure inner){ if(inner!=null){ children = new Figure[1]; children[0] = inner; } else { children = EMPTY_ARRAY; } innerFig = inner; } public double getGrowFactor(Dimension d){ return Math.max(prop.get2DReal(d, GROW), 1.0 / innerFig.prop.get2DReal(d,SHRINK)); } @Override public void computeMinSize() { if(innerFig!=null){ for(Dimension d : HOR_VER){ minSize.set(d, innerFig.minSize.get(d) * getGrowFactor(d)); minSize.setMax(d, innerFig.minSize.get(d) + 2 * prop.get2DReal(d, GAP)); - if(!innerFig.resizable.get(d) && prop.is2DPropertySet(d, GROW)){ - resizable.set(d,false); - } +// if(!innerFig.resizable.get(d) && prop.is2DPropertySet(d, GROW)){ +// resizable.set(d,false); +// } } } } @Override public void resizeElement(Rectangle view) { if(innerFig == null) return; for(Dimension d : HOR_VER){ double innerDesiredWidth = size.get(d) / getGrowFactor(d); innerDesiredWidth = Math.min(size.get(d) - 2 * prop.get2DReal(d, GAP), innerDesiredWidth); innerFig.size.set(d, innerDesiredWidth); innerFig.localLocation.set(d, (size.get(d) - innerFig.size.get(d)) * innerFig.prop.get2DReal(d, ALIGN)); } } }
true
true
public void computeMinSize() { if(innerFig!=null){ for(Dimension d : HOR_VER){ minSize.set(d, innerFig.minSize.get(d) * getGrowFactor(d)); minSize.setMax(d, innerFig.minSize.get(d) + 2 * prop.get2DReal(d, GAP)); if(!innerFig.resizable.get(d) && prop.is2DPropertySet(d, GROW)){ resizable.set(d,false); } } } }
public void computeMinSize() { if(innerFig!=null){ for(Dimension d : HOR_VER){ minSize.set(d, innerFig.minSize.get(d) * getGrowFactor(d)); minSize.setMax(d, innerFig.minSize.get(d) + 2 * prop.get2DReal(d, GAP)); // if(!innerFig.resizable.get(d) && prop.is2DPropertySet(d, GROW)){ // resizable.set(d,false); // } } } }
diff --git a/dev/core/src/com/google/gwt/dev/jdt/WebModeCompilerFrontEnd.java b/dev/core/src/com/google/gwt/dev/jdt/WebModeCompilerFrontEnd.java index ef33ecb51..a6c36cc6c 100644 --- a/dev/core/src/com/google/gwt/dev/jdt/WebModeCompilerFrontEnd.java +++ b/dev/core/src/com/google/gwt/dev/jdt/WebModeCompilerFrontEnd.java @@ -1,303 +1,304 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.dev.jdt; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.dev.javac.CompilationState; import com.google.gwt.dev.javac.CompilationUnit; import com.google.gwt.dev.javac.CompiledClass; import com.google.gwt.dev.javac.JdtCompiler.CompilationUnitAdapter; import com.google.gwt.dev.jdt.FindDeferredBindingSitesVisitor.MessageSendSite; import com.google.gwt.dev.jjs.impl.FragmentLoaderCreator; import com.google.gwt.dev.util.Empty; import com.google.gwt.dev.util.JsniRef; import com.google.gwt.dev.util.Memory; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Provides a reusable front-end based on the JDT compiler that incorporates * GWT-specific concepts such as JSNI and deferred binding. */ public class WebModeCompilerFrontEnd extends AbstractCompiler { public static CompilationUnitDeclaration[] getCompilationUnitDeclarations( TreeLogger logger, String[] seedTypeNames, CompilationState compilationState, RebindPermutationOracle rebindPermOracle) throws UnableToCompleteException { return new WebModeCompilerFrontEnd(compilationState, rebindPermOracle).getCompilationUnitDeclarations( logger, seedTypeNames); } private final FragmentLoaderCreator fragmentLoaderCreator; private final RebindPermutationOracle rebindPermOracle; /** * Construct a WebModeCompilerFrontEnd. The reason a * {@link FragmentLoaderCreator} needs to be passed in is that it uses * generator infrastructure, and therefore needs access to more parts of the * compiler than WebModeCompilerFrontEnd currently has. */ private WebModeCompilerFrontEnd(CompilationState compilationState, RebindPermutationOracle rebindPermOracle) { super(compilationState, false); this.rebindPermOracle = rebindPermOracle; this.fragmentLoaderCreator = new FragmentLoaderCreator( rebindPermOracle.getGeneratorContext()); } /** * Build the initial set of compilation units. */ public CompilationUnitDeclaration[] getCompilationUnitDeclarations( TreeLogger logger, String[] seedTypeNames) throws UnableToCompleteException { TypeOracle oracle = compilationState.getTypeOracle(); Set<JClassType> intfTypes = oracle.getSingleJsoImplInterfaces(); Map<String, CompiledClass> classMapBySource = compilationState.getClassFileMapBySource(); /* * The alreadyAdded set prevents duplicate CompilationUnits from being added * to the icu list in the case of multiple JSO implementations as inner * classes in the same top-level class or seed classes as SingleJsoImpls * (e.g. JSO itself as the SingleImpl for all tag interfaces). */ Set<CompilationUnit> alreadyAdded = new HashSet<CompilationUnit>(); List<ICompilationUnit> icus = new ArrayList<ICompilationUnit>( seedTypeNames.length + intfTypes.size()); for (String seedTypeName : seedTypeNames) { CompilationUnit unit = getUnitForType(logger, classMapBySource, seedTypeName); if (alreadyAdded.add(unit)) { icus.add(new CompilationUnitAdapter(unit)); } else { logger.log(TreeLogger.WARN, "Duplicate compilation unit '" + unit.getDisplayLocation() + "'in seed types"); } } /* * Add all SingleJsoImpl types that we know about. It's likely that the * concrete types are never explicitly referenced from the seed types. */ for (JClassType intf : intfTypes) { String implName = oracle.getSingleJsoImpl(intf).getQualifiedSourceName(); CompilationUnit unit = getUnitForType(logger, classMapBySource, implName); if (alreadyAdded.add(unit)) { icus.add(new CompilationUnitAdapter(unit)); logger.log(TreeLogger.SPAM, "Forced compilation of unit '" + unit.getDisplayLocation() + "' becasue it contains a SingleJsoImpl type"); } } /* * Compile, which will pull in everything else via * doFindAdditionalTypesUsingMagic() */ CompilationUnitDeclaration[] cuds = compile(logger, icus.toArray(new ICompilationUnit[icus.size()])); Memory.maybeDumpMemory("WebModeCompiler"); return cuds; } @Override protected void doCompilationUnitDeclarationValidation( CompilationUnitDeclaration cud, TreeLogger logger) { /* * Anything that makes it here was already checked by AstCompiler while * building TypeOracle; no need to rerun checks. */ } /** * Pull in types referenced only via JSNI. */ @Override protected String[] doFindAdditionalTypesUsingJsni(TreeLogger logger, CompilationUnitDeclaration cud) { FindJsniRefVisitor v = new FindJsniRefVisitor(); cud.traverse(v, cud.scope); Set<String> jsniRefs = v.getJsniRefs(); Set<String> dependentTypeNames = new HashSet<String>(); for (String jsniRef : jsniRefs) { JsniRef parsed = JsniRef.parse(jsniRef); if (parsed != null) { // If we fail to parse, don't add a class reference. dependentTypeNames.add(parsed.className()); } } return dependentTypeNames.toArray(Empty.STRINGS); } /** * Pull in types implicitly referenced through rebind answers. */ @Override protected String[] doFindAdditionalTypesUsingRebinds(TreeLogger logger, CompilationUnitDeclaration cud) { Set<String> dependentTypeNames = new HashSet<String>(); // Find all the deferred binding request types. FindDeferredBindingSitesVisitor v = new FindDeferredBindingSitesVisitor(); cud.traverse(v, cud.scope); Map<String, MessageSendSite> requestedTypes = v.getSites(); Map<String, String[]> rebindAnswers = new HashMap<String, String[]>(); boolean doFinish = false; // For each, ask the host for every possible deferred binding answer. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); try { String[] resultTypes = rebindPermOracle.getAllPossibleRebindAnswers( logger, reqType); rebindAnswers.put(reqType, resultTypes); Collections.addAll(dependentTypeNames, resultTypes); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to resolve '" + reqType + "' via deferred binding"); + rebindAnswers.put(reqType, new String[0]); } } /* * Create a a fragment loader for each GWT.runAsync call. They must be * created now, rather than in ReplaceRunAsyncs, because all generated * classes need to be created before GenerateJavaAST. Note that the loaders * created are not yet associated with the specific sites. The present task * is only to make sure that enough loaders exist. The real association * between loaders and runAsync sites will be made in ReplaceRunAsyncs. */ for (MessageSendSite site : v.getRunAsyncSites()) { String resultType; try { resultType = fragmentLoaderCreator.create(logger); dependentTypeNames.add(resultType); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to create a runAsync fragment loader"); } } if (doFinish) { try { rebindPermOracle.getGeneratorContext().finish(logger); } catch (UnableToCompleteException e) { throw new RuntimeException("Unable to commit generated files", e); } } // Sanity check all rebind answers. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); String[] resultTypes = rebindAnswers.get(reqType); // Check that each result is instantiable. for (String typeName : resultTypes) { checkRebindResultInstantiable(site, typeName); } } return dependentTypeNames.toArray(Empty.STRINGS); } private void checkRebindResultInstantiable(MessageSendSite site, String typeName) { /* * This causes the compiler to find the additional type, possibly winding * its back to ask for the compilation unit from the source oracle. */ ReferenceBinding type = resolvePossiblyNestedType(typeName); // Sanity check rebind results. if (type == null) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' could not be found"); return; } if (!type.isClass()) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' must be a class"); return; } if (type.isAbstract()) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' cannot be abstract"); return; } if (type.isNestedType() && !type.isStatic()) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' cannot be a non-static nested class"); return; } if (type.isLocalType()) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' cannot be a local class"); return; } // Look for a noArg ctor. MethodBinding noArgCtor = type.getExactConstructor(TypeBinding.NO_PARAMETERS); if (noArgCtor == null) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Rebind result '" + typeName + "' has no default (zero argument) constructors"); return; } } /** * Get the CompilationUnit for a named type or throw an * UnableToCompleteException. */ private CompilationUnit getUnitForType(TreeLogger logger, Map<String, CompiledClass> classMapBySource, String typeName) throws UnableToCompleteException { CompiledClass compiledClass = classMapBySource.get(typeName); if (compiledClass == null) { logger.log(TreeLogger.ERROR, "Unable to find compilation unit for type '" + typeName + "'"); throw new UnableToCompleteException(); } assert compiledClass.getUnit() != null; return compiledClass.getUnit(); } }
true
true
protected String[] doFindAdditionalTypesUsingRebinds(TreeLogger logger, CompilationUnitDeclaration cud) { Set<String> dependentTypeNames = new HashSet<String>(); // Find all the deferred binding request types. FindDeferredBindingSitesVisitor v = new FindDeferredBindingSitesVisitor(); cud.traverse(v, cud.scope); Map<String, MessageSendSite> requestedTypes = v.getSites(); Map<String, String[]> rebindAnswers = new HashMap<String, String[]>(); boolean doFinish = false; // For each, ask the host for every possible deferred binding answer. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); try { String[] resultTypes = rebindPermOracle.getAllPossibleRebindAnswers( logger, reqType); rebindAnswers.put(reqType, resultTypes); Collections.addAll(dependentTypeNames, resultTypes); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to resolve '" + reqType + "' via deferred binding"); } } /* * Create a a fragment loader for each GWT.runAsync call. They must be * created now, rather than in ReplaceRunAsyncs, because all generated * classes need to be created before GenerateJavaAST. Note that the loaders * created are not yet associated with the specific sites. The present task * is only to make sure that enough loaders exist. The real association * between loaders and runAsync sites will be made in ReplaceRunAsyncs. */ for (MessageSendSite site : v.getRunAsyncSites()) { String resultType; try { resultType = fragmentLoaderCreator.create(logger); dependentTypeNames.add(resultType); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to create a runAsync fragment loader"); } } if (doFinish) { try { rebindPermOracle.getGeneratorContext().finish(logger); } catch (UnableToCompleteException e) { throw new RuntimeException("Unable to commit generated files", e); } } // Sanity check all rebind answers. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); String[] resultTypes = rebindAnswers.get(reqType); // Check that each result is instantiable. for (String typeName : resultTypes) { checkRebindResultInstantiable(site, typeName); } } return dependentTypeNames.toArray(Empty.STRINGS); }
protected String[] doFindAdditionalTypesUsingRebinds(TreeLogger logger, CompilationUnitDeclaration cud) { Set<String> dependentTypeNames = new HashSet<String>(); // Find all the deferred binding request types. FindDeferredBindingSitesVisitor v = new FindDeferredBindingSitesVisitor(); cud.traverse(v, cud.scope); Map<String, MessageSendSite> requestedTypes = v.getSites(); Map<String, String[]> rebindAnswers = new HashMap<String, String[]>(); boolean doFinish = false; // For each, ask the host for every possible deferred binding answer. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); try { String[] resultTypes = rebindPermOracle.getAllPossibleRebindAnswers( logger, reqType); rebindAnswers.put(reqType, resultTypes); Collections.addAll(dependentTypeNames, resultTypes); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to resolve '" + reqType + "' via deferred binding"); rebindAnswers.put(reqType, new String[0]); } } /* * Create a a fragment loader for each GWT.runAsync call. They must be * created now, rather than in ReplaceRunAsyncs, because all generated * classes need to be created before GenerateJavaAST. Note that the loaders * created are not yet associated with the specific sites. The present task * is only to make sure that enough loaders exist. The real association * between loaders and runAsync sites will be made in ReplaceRunAsyncs. */ for (MessageSendSite site : v.getRunAsyncSites()) { String resultType; try { resultType = fragmentLoaderCreator.create(logger); dependentTypeNames.add(resultType); doFinish = true; } catch (UnableToCompleteException e) { FindDeferredBindingSitesVisitor.reportRebindProblem(site, "Failed to create a runAsync fragment loader"); } } if (doFinish) { try { rebindPermOracle.getGeneratorContext().finish(logger); } catch (UnableToCompleteException e) { throw new RuntimeException("Unable to commit generated files", e); } } // Sanity check all rebind answers. for (Map.Entry<String, MessageSendSite> entry : requestedTypes.entrySet()) { String reqType = entry.getKey(); MessageSendSite site = entry.getValue(); String[] resultTypes = rebindAnswers.get(reqType); // Check that each result is instantiable. for (String typeName : resultTypes) { checkRebindResultInstantiable(site, typeName); } } return dependentTypeNames.toArray(Empty.STRINGS); }
diff --git a/src/com/TrackApp/GearComparisonActivity.java b/src/com/TrackApp/GearComparisonActivity.java index 7158d06..d025968 100644 --- a/src/com/TrackApp/GearComparisonActivity.java +++ b/src/com/TrackApp/GearComparisonActivity.java @@ -1,240 +1,240 @@ package com.TrackApp; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.TextView; import com.TrackApp.NumberPicker; import com.TrackApp.Gear_Inch_Calc; public class GearComparisonActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.gear_comparison); //Set up of Front Ring Select0r final NumberPicker frontRing1 = (NumberPicker)findViewById(R.id.FrontRing1); frontRing1.setRange(30, 65); frontRing1.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog1 = (NumberPicker)findViewById(R.id.RearCog1); rearCog1.setRange(10,23); rearCog1.setCurrent(14); //Set up of Front Ring Select0r final NumberPicker frontRing2 = (NumberPicker)findViewById(R.id.FrontRing2); frontRing2.setRange(30, 65); frontRing2.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog2 = (NumberPicker)findViewById(R.id.RearCog2); rearCog2.setRange(10,23); rearCog2.setCurrent(14); //Cadence final SeekBar cadence= (SeekBar)findViewById(R.id.GCCadenceBar); cadence.setMax(200); cadence.setProgress(90); //TextViews final TextView cadence_label = (TextView)findViewById(R.id.Cadence); final TextView gearinch1 = (TextView)findViewById(R.id.GearInchOne); final TextView gearinch2 = (TextView)findViewById(R.id.GearInchTwo); final TextView rollout1 = (TextView)findViewById(R.id.Rollout_one); final TextView rollout2 = (TextView)findViewById(R.id.Rollout_two); final TextView speed1 = (TextView)findViewById(R.id.Speed_1); final TextView speed2 = (TextView)findViewById(R.id.Speed_2); //Distance Times final List<TextView> Time_TextViews_1 = new ArrayList<TextView>(); final List<TextView> Time_TextViews_2 = new ArrayList<TextView>(); final List<Integer> Distance = new ArrayList<Integer>(); final TextView twohm1 = (TextView)findViewById(R.id.two_hund_m_1_time); final TextView twohm2 = (TextView)findViewById(R.id.two_hund_m_2_time); Time_TextViews_1.add(twohm1); Time_TextViews_2.add(twohm2); Distance.add(200); final TextView twofifty1 = (TextView)findViewById(R.id.two_fifty_m_1_time); final TextView twofifty2 = (TextView)findViewById(R.id.two_fifty_m_2_time); Time_TextViews_1.add(twofifty1); Time_TextViews_2.add(twofifty2); Distance.add(250); final TextView TTT1 = (TextView)findViewById(R.id.Three_thirdy_three_m_1_time); final TextView TTT2 = (TextView)findViewById(R.id.Three_thirdy_three_m_2_time); Time_TextViews_1.add(TTT1); Time_TextViews_2.add(TTT2); Distance.add(333); final TextView fourhm1 = (TextView)findViewById(R.id.four_hundred_m_1_time); final TextView fourhm2 = (TextView)findViewById(R.id.four_hundred_m_2_time); Time_TextViews_1.add(fourhm1); Time_TextViews_2.add(fourhm2); Distance.add(400); final TextView fivehm1 = (TextView)findViewById(R.id.five_hundred_m_1_time); final TextView fivehm2 = (TextView)findViewById(R.id.five_hundred_m_2_time); Time_TextViews_1.add(fivehm1); Time_TextViews_2.add(fivehm2); Distance.add(500); final TextView onek1 = (TextView)findViewById(R.id.one_k_1_time); final TextView onek2 = (TextView)findViewById(R.id.one_k_2_time); Time_TextViews_1.add(onek1); Time_TextViews_2.add(onek2); Distance.add(1000); //Listener for change to Front Ring Selector frontRing1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog1.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Times Update_Times(Time_TextViews_1, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing1.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Distance Times Update_Times(Time_TextViews_1, Distance, from_Rear, cadence.getProgress()); } }); frontRing2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog2.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Times Update_Times(Time_TextViews_2, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing2.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Distance Times Update_Times(Time_TextViews_2, Distance, from_Rear, cadence.getProgress()); } }); cadence.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { Gear_Inch_Calc gear_1 = new Gear_Inch_Calc(frontRing1.getCurrent(),rearCog1.getCurrent()); - CharSequence speed_1 = (CharSequence)((Double)gear_1.KPH_Speed(seekBar.getProgress())).toString(); - speed1.setText(speed_1); + CharSequence speed = (CharSequence)((Double)gear_1.KPH_Speed(seekBar.getProgress())).toString(); + speed1.setText(speed); Update_Times(Time_TextViews_1, Distance, gear_1, cadence.getProgress()); Gear_Inch_Calc gear_2 = new Gear_Inch_Calc(frontRing2.getCurrent(), rearCog2.getCurrent()); - CharSequence speed_2 = (CharSequence)((Double)gear_2.KPH_Speed(seekBar.getProgress())).toString(); - speed2.setText(speed_2); + speed = (CharSequence)((Double)gear_2.KPH_Speed(seekBar.getProgress())).toString(); + speed2.setText(speed); Update_Times(Time_TextViews_2, Distance, gear_2, cadence.getProgress()); } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { CharSequence x = ((Integer)progress).toString(); cadence_label.setText(x); } }); } //Abstraction to update times private void Update_Times(List<TextView> views, List<Integer> Distances, Gear_Inch_Calc gear, int cadence) { for(int i=0; i<views.size(); i++) { views.get(i).setText((CharSequence) gear.Pretty_Print( gear.Time_To_Complete(cadence, Distances.get(i)))); } } }
false
true
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.gear_comparison); //Set up of Front Ring Select0r final NumberPicker frontRing1 = (NumberPicker)findViewById(R.id.FrontRing1); frontRing1.setRange(30, 65); frontRing1.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog1 = (NumberPicker)findViewById(R.id.RearCog1); rearCog1.setRange(10,23); rearCog1.setCurrent(14); //Set up of Front Ring Select0r final NumberPicker frontRing2 = (NumberPicker)findViewById(R.id.FrontRing2); frontRing2.setRange(30, 65); frontRing2.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog2 = (NumberPicker)findViewById(R.id.RearCog2); rearCog2.setRange(10,23); rearCog2.setCurrent(14); //Cadence final SeekBar cadence= (SeekBar)findViewById(R.id.GCCadenceBar); cadence.setMax(200); cadence.setProgress(90); //TextViews final TextView cadence_label = (TextView)findViewById(R.id.Cadence); final TextView gearinch1 = (TextView)findViewById(R.id.GearInchOne); final TextView gearinch2 = (TextView)findViewById(R.id.GearInchTwo); final TextView rollout1 = (TextView)findViewById(R.id.Rollout_one); final TextView rollout2 = (TextView)findViewById(R.id.Rollout_two); final TextView speed1 = (TextView)findViewById(R.id.Speed_1); final TextView speed2 = (TextView)findViewById(R.id.Speed_2); //Distance Times final List<TextView> Time_TextViews_1 = new ArrayList<TextView>(); final List<TextView> Time_TextViews_2 = new ArrayList<TextView>(); final List<Integer> Distance = new ArrayList<Integer>(); final TextView twohm1 = (TextView)findViewById(R.id.two_hund_m_1_time); final TextView twohm2 = (TextView)findViewById(R.id.two_hund_m_2_time); Time_TextViews_1.add(twohm1); Time_TextViews_2.add(twohm2); Distance.add(200); final TextView twofifty1 = (TextView)findViewById(R.id.two_fifty_m_1_time); final TextView twofifty2 = (TextView)findViewById(R.id.two_fifty_m_2_time); Time_TextViews_1.add(twofifty1); Time_TextViews_2.add(twofifty2); Distance.add(250); final TextView TTT1 = (TextView)findViewById(R.id.Three_thirdy_three_m_1_time); final TextView TTT2 = (TextView)findViewById(R.id.Three_thirdy_three_m_2_time); Time_TextViews_1.add(TTT1); Time_TextViews_2.add(TTT2); Distance.add(333); final TextView fourhm1 = (TextView)findViewById(R.id.four_hundred_m_1_time); final TextView fourhm2 = (TextView)findViewById(R.id.four_hundred_m_2_time); Time_TextViews_1.add(fourhm1); Time_TextViews_2.add(fourhm2); Distance.add(400); final TextView fivehm1 = (TextView)findViewById(R.id.five_hundred_m_1_time); final TextView fivehm2 = (TextView)findViewById(R.id.five_hundred_m_2_time); Time_TextViews_1.add(fivehm1); Time_TextViews_2.add(fivehm2); Distance.add(500); final TextView onek1 = (TextView)findViewById(R.id.one_k_1_time); final TextView onek2 = (TextView)findViewById(R.id.one_k_2_time); Time_TextViews_1.add(onek1); Time_TextViews_2.add(onek2); Distance.add(1000); //Listener for change to Front Ring Selector frontRing1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog1.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Times Update_Times(Time_TextViews_1, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing1.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Distance Times Update_Times(Time_TextViews_1, Distance, from_Rear, cadence.getProgress()); } }); frontRing2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog2.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Times Update_Times(Time_TextViews_2, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing2.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Distance Times Update_Times(Time_TextViews_2, Distance, from_Rear, cadence.getProgress()); } }); cadence.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { Gear_Inch_Calc gear_1 = new Gear_Inch_Calc(frontRing1.getCurrent(),rearCog1.getCurrent()); CharSequence speed_1 = (CharSequence)((Double)gear_1.KPH_Speed(seekBar.getProgress())).toString(); speed1.setText(speed_1); Update_Times(Time_TextViews_1, Distance, gear_1, cadence.getProgress()); Gear_Inch_Calc gear_2 = new Gear_Inch_Calc(frontRing2.getCurrent(), rearCog2.getCurrent()); CharSequence speed_2 = (CharSequence)((Double)gear_2.KPH_Speed(seekBar.getProgress())).toString(); speed2.setText(speed_2); Update_Times(Time_TextViews_2, Distance, gear_2, cadence.getProgress()); } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { CharSequence x = ((Integer)progress).toString(); cadence_label.setText(x); } }); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.gear_comparison); //Set up of Front Ring Select0r final NumberPicker frontRing1 = (NumberPicker)findViewById(R.id.FrontRing1); frontRing1.setRange(30, 65); frontRing1.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog1 = (NumberPicker)findViewById(R.id.RearCog1); rearCog1.setRange(10,23); rearCog1.setCurrent(14); //Set up of Front Ring Select0r final NumberPicker frontRing2 = (NumberPicker)findViewById(R.id.FrontRing2); frontRing2.setRange(30, 65); frontRing2.setCurrent(48); //Set up of Cog Selector final NumberPicker rearCog2 = (NumberPicker)findViewById(R.id.RearCog2); rearCog2.setRange(10,23); rearCog2.setCurrent(14); //Cadence final SeekBar cadence= (SeekBar)findViewById(R.id.GCCadenceBar); cadence.setMax(200); cadence.setProgress(90); //TextViews final TextView cadence_label = (TextView)findViewById(R.id.Cadence); final TextView gearinch1 = (TextView)findViewById(R.id.GearInchOne); final TextView gearinch2 = (TextView)findViewById(R.id.GearInchTwo); final TextView rollout1 = (TextView)findViewById(R.id.Rollout_one); final TextView rollout2 = (TextView)findViewById(R.id.Rollout_two); final TextView speed1 = (TextView)findViewById(R.id.Speed_1); final TextView speed2 = (TextView)findViewById(R.id.Speed_2); //Distance Times final List<TextView> Time_TextViews_1 = new ArrayList<TextView>(); final List<TextView> Time_TextViews_2 = new ArrayList<TextView>(); final List<Integer> Distance = new ArrayList<Integer>(); final TextView twohm1 = (TextView)findViewById(R.id.two_hund_m_1_time); final TextView twohm2 = (TextView)findViewById(R.id.two_hund_m_2_time); Time_TextViews_1.add(twohm1); Time_TextViews_2.add(twohm2); Distance.add(200); final TextView twofifty1 = (TextView)findViewById(R.id.two_fifty_m_1_time); final TextView twofifty2 = (TextView)findViewById(R.id.two_fifty_m_2_time); Time_TextViews_1.add(twofifty1); Time_TextViews_2.add(twofifty2); Distance.add(250); final TextView TTT1 = (TextView)findViewById(R.id.Three_thirdy_three_m_1_time); final TextView TTT2 = (TextView)findViewById(R.id.Three_thirdy_three_m_2_time); Time_TextViews_1.add(TTT1); Time_TextViews_2.add(TTT2); Distance.add(333); final TextView fourhm1 = (TextView)findViewById(R.id.four_hundred_m_1_time); final TextView fourhm2 = (TextView)findViewById(R.id.four_hundred_m_2_time); Time_TextViews_1.add(fourhm1); Time_TextViews_2.add(fourhm2); Distance.add(400); final TextView fivehm1 = (TextView)findViewById(R.id.five_hundred_m_1_time); final TextView fivehm2 = (TextView)findViewById(R.id.five_hundred_m_2_time); Time_TextViews_1.add(fivehm1); Time_TextViews_2.add(fivehm2); Distance.add(500); final TextView onek1 = (TextView)findViewById(R.id.one_k_1_time); final TextView onek2 = (TextView)findViewById(R.id.one_k_2_time); Time_TextViews_1.add(onek1); Time_TextViews_2.add(onek2); Distance.add(1000); //Listener for change to Front Ring Selector frontRing1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog1.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Times Update_Times(Time_TextViews_1, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog1.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing1.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch1.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout1.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed1.setText(x); //Update Distance Times Update_Times(Time_TextViews_1, Distance, from_Rear, cadence.getProgress()); } }); frontRing2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Front = new Gear_Inch_Calc(newVal,rearCog2.getCurrent()); CharSequence x; Double y= from_Front.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Front.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Front.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Times Update_Times(Time_TextViews_2, Distance, from_Front, cadence.getProgress()); } }); //Listener for change to Cog Selector rearCog2.setOnChangeListener(new NumberPicker.OnChangedListener() { public void onChanged(NumberPicker picker, int oldVal, int newVal) { //Change Gear Inches Gear_Inch_Calc from_Rear = new Gear_Inch_Calc(frontRing2.getCurrent(),newVal); CharSequence x; Double y= from_Rear.getGearInches(); x = (CharSequence) y.toString(); gearinch2.setText(x); //Change Rollout x = (CharSequence)((Double)from_Rear.getDistanceTraveled()).toString(); rollout2.setText(x); //Change Speed double speed = from_Rear.KPH_Speed(cadence.getProgress()); x =(CharSequence)((Double)speed).toString(); speed2.setText(x); //Update Distance Times Update_Times(Time_TextViews_2, Distance, from_Rear, cadence.getProgress()); } }); cadence.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { Gear_Inch_Calc gear_1 = new Gear_Inch_Calc(frontRing1.getCurrent(),rearCog1.getCurrent()); CharSequence speed = (CharSequence)((Double)gear_1.KPH_Speed(seekBar.getProgress())).toString(); speed1.setText(speed); Update_Times(Time_TextViews_1, Distance, gear_1, cadence.getProgress()); Gear_Inch_Calc gear_2 = new Gear_Inch_Calc(frontRing2.getCurrent(), rearCog2.getCurrent()); speed = (CharSequence)((Double)gear_2.KPH_Speed(seekBar.getProgress())).toString(); speed2.setText(speed); Update_Times(Time_TextViews_2, Distance, gear_2, cadence.getProgress()); } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { CharSequence x = ((Integer)progress).toString(); cadence_label.setText(x); } }); }
diff --git a/src/org/jets3t/service/utils/FileComparer.java b/src/org/jets3t/service/utils/FileComparer.java index a7ec07d..f812513 100644 --- a/src/org/jets3t/service/utils/FileComparer.java +++ b/src/org/jets3t/service/utils/FileComparer.java @@ -1,568 +1,568 @@ /* * jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service) * This is a java.net project, see https://jets3t.dev.java.net/ * * Copyright 2006 James Murty * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jets3t.service.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jets3t.service.Constants; import org.jets3t.service.Jets3tProperties; import org.jets3t.service.S3Service; import org.jets3t.service.S3ServiceException; import org.jets3t.service.io.BytesProgressWatcher; import org.jets3t.service.io.ProgressMonitoredInputStream; import org.jets3t.service.model.S3Bucket; import org.jets3t.service.model.S3Object; import org.jets3t.service.multithread.GetObjectHeadsEvent; import org.jets3t.service.multithread.S3ServiceEventAdaptor; import org.jets3t.service.multithread.S3ServiceEventListener; import org.jets3t.service.multithread.S3ServiceMulti; /** * File comparison utility to compare files on the local computer with objects present in an S3 * account and determine whether there are any differences. This utility contains methods to * build maps of the contents of the local file system or S3 account for comparison, and * <tt>buildDiscrepancyLists</tt> methods to find differences in these maps. * <p> * File comparisons are based primarily on MD5 hashes of the files' contents. If a local file does * not match an object in S3 with the same name, this utility determine which of the items is * newer by comparing the last modified dates. * * @author James Murty */ public class FileComparer { private static final Log log = LogFactory.getLog(FileComparer.class); /** * If a <code>.jets3t-ignore</code> file is present in the given directory, the file is read * and all the paths contained in it are coverted to regular expression Pattern objects. * * @param directory * a directory that may contain a <code>.jets3t-ignore</code> file. If this parameter is null * or is actually a file and not a directory, an empty list will be returned. * * @return * a list of Pattern objects representing the paths in the ignore file. If there is no ignore * file, or if it has no contents, the list returned will be empty. */ protected static List buildIgnoreRegexpList(File directory) { ArrayList ignorePatternList = new ArrayList(); if (directory == null || !directory.isDirectory()) { return ignorePatternList; } File jets3tIgnoreFile = new File(directory, Constants.JETS3T_IGNORE_FILENAME); if (jets3tIgnoreFile.exists() && jets3tIgnoreFile.canRead()) { log.debug("Found ignore file: " + jets3tIgnoreFile.getPath()); try { String ignorePaths = ServiceUtils.readInputStreamToString( new FileInputStream(jets3tIgnoreFile)); StringTokenizer st = new StringTokenizer(ignorePaths.trim(), "\n"); while (st.hasMoreTokens()) { String ignorePath = st.nextToken(); // Convert path to RegExp. String ignoreRegexp = ignorePath; ignoreRegexp = ignoreRegexp.replaceAll("\\.", "\\\\."); ignoreRegexp = ignoreRegexp.replaceAll("\\*", ".*"); ignoreRegexp = ignoreRegexp.replaceAll("\\?", "."); Pattern pattern = Pattern.compile(ignoreRegexp); log.debug("Ignore path '" + ignorePath + "' has become the regexp: " + pattern.pattern()); ignorePatternList.add(pattern); } } catch (IOException e) { log.error("Failed to read contents of ignore file '" + jets3tIgnoreFile.getPath() + "'", e); } } if (Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.skip-upload-of-md5-files", false)) { Pattern pattern = Pattern.compile(".*\\.md5"); log.debug("Skipping upload of pre-computed MD5 files with path '*.md5' using the regexp: " + pattern.pattern()); ignorePatternList.add(pattern); } return ignorePatternList; } /** * Determines whether a file should be ignored, based on whether it matches a regular expression * Pattern in the provided ignore list. * * @param ignorePatternList * a list of Pattern objects representing the file names to ignore. * @param file * a file that will either be ignored or not, depending on whether it matches an ignore Pattern. * * @return * true if the file should be ignored, false otherwise. */ protected static boolean isIgnored(List ignorePatternList, File file) { Iterator patternIter = ignorePatternList.iterator(); while (patternIter.hasNext()) { Pattern pattern = (Pattern) patternIter.next(); if (pattern.matcher(file.getName()).matches()) { log.debug("Ignoring " + (file.isDirectory() ? "directory" : "file") + " matching pattern '" + pattern.pattern() + "': " + file.getName()); return true; } } return false; } /** * Builds a File Map containing the given files. If any of the given files are actually * directories, the contents of the directory are included. * <p> * File keys are delimited with '/' characters. * <p> * Any file or directory matching a path in a <code>.jets3t-ignore</code> file will be ignored. * * @param files * the set of files/directories to include in the file map. * @param includeDirectories * If true all directories, including empty ones, will be included in the Map. These directories * will be mere place-holder objects with the content type {@link Mimetypes#MIMETYPE_JETS3T_DIRECTORY}. * If this variable is false directory objects will not be included in the Map, and it will not * be possible to store empty directories in S3. * * @return * a Map of file path keys to File objects. */ public static Map buildFileMap(File[] files, boolean includeDirectories) { // Build map of files proposed for upload. HashMap fileMap = new HashMap(); for (int i = 0; i < files.length; i++) { List ignorePatternList = buildIgnoreRegexpList(files[i].getParentFile()); if (!isIgnored(ignorePatternList, files[i])) { if (!files[i].isDirectory() || includeDirectories) { fileMap.put(files[i].getName(), files[i]); } if (files[i].isDirectory()) { buildFileMapImpl(files[i], files[i].getName() + Constants.FILE_PATH_DELIM, fileMap, includeDirectories); } } } return fileMap; } /** * Builds a File Map containing all the files and directories inside the given root directory, * where the map's key for each file is the relative path to the file. * <p> * File keys are delimited with '/' characters. * <p> * Any file or directory matching a path in a <code>.jets3t-ignore</code> file will be ignored. * * @see #buildDiscrepancyLists(Map, Map) * @see #buildS3ObjectMap(S3Service, S3Bucket, String, S3Object[], S3ServiceEventListener) * * @param rootDirectory * The root directory containing the files/directories of interest. The root directory is <b>not</b> * included in the result map. * @param fileKeyPrefix * A prefix added to each file path key in the map, e.g. the name of the root directory the * files belong to. If provided, a '/' suffix is always added to the end of the prefix. If null * or empty, no prefix is used. * @param includeDirectories * If true all directories, including empty ones, will be included in the Map. These directories * will be mere place-holder objects with the content type {@link Mimetypes#MIMETYPE_JETS3T_DIRECTORY}. * If this variable is false directory objects will not be included in the Map, and it will not * be possible to store empty directories in S3. * * @return A Map of file path keys to File objects. */ public static Map buildFileMap(File rootDirectory, String fileKeyPrefix, boolean includeDirectories) { HashMap fileMap = new HashMap(); List ignorePatternList = buildIgnoreRegexpList(rootDirectory); if (!isIgnored(ignorePatternList, rootDirectory)) { if (fileKeyPrefix == null || fileKeyPrefix.length() == 0) { fileKeyPrefix = ""; } else { if (!fileKeyPrefix.endsWith(Constants.FILE_PATH_DELIM)) { fileKeyPrefix += Constants.FILE_PATH_DELIM; } } buildFileMapImpl(rootDirectory, fileKeyPrefix, fileMap, includeDirectories); } return fileMap; } /** * Recursively builds a File Map containing all the files and directories inside the given directory, * where the map's key for each file is the relative path to the file. * <p> * File keys are delimited with '/' characters. * <p> * Any file or directory matching a path in a <code>.jets3t-ignore</code> file will be ignored. * * @param directory * The directory containing the files/directories of interest. The directory is <b>not</b> * included in the result map. * @param fileKeyPrefix * A prefix added to each file path key in the map, e.g. the name of the root directory the * files belong to. This prefix <b>must</b> end with a '/' character. * @param fileMap * a map of path keys to File objects, that this method adds items to. * @param includeDirectories * If true all directories, including empty ones, will be included in the Map. These directories * will be mere place-holder objects with the content type {@link Mimetypes#MIMETYPE_JETS3T_DIRECTORY}. * If this variable is false directory objects will not be included in the Map, and it will not * be possible to store empty directories in S3. */ protected static void buildFileMapImpl(File directory, String fileKeyPrefix, Map fileMap, boolean includeDirectories) { List ignorePatternList = buildIgnoreRegexpList(directory); File children[] = directory.listFiles(); for (int i = 0; children != null && i < children.length; i++) { if (!isIgnored(ignorePatternList, children[i])) { if (!children[i].isDirectory() || includeDirectories) { fileMap.put(fileKeyPrefix + children[i].getName(), children[i]); } if (children[i].isDirectory()) { buildFileMapImpl(children[i], fileKeyPrefix + children[i].getName() + "/", fileMap, includeDirectories); } } } } /** * Builds an S3 Object Map containing all the objects within the given target path, * where the map's key for each object is the relative path to the object. * * @see #buildDiscrepancyLists(Map, Map) * @see #buildFileMap(File, String, boolean) * * @param s3Service * @param bucket * @param targetPath * @return * maping of keys/S3Objects * @throws S3ServiceException */ public static Map buildS3ObjectMap(S3Service s3Service, S3Bucket bucket, String targetPath, S3ServiceEventListener s3ServiceEventListener) throws S3ServiceException { String prefix = (targetPath.length() > 0 ? targetPath : null); S3Object[] s3ObjectsIncomplete = s3Service.listObjects(bucket, prefix, null); return buildS3ObjectMap(s3Service, bucket, targetPath, s3ObjectsIncomplete, s3ServiceEventListener); } /** * Builds an S3 Object Map containing all the given objects, by retrieving HEAD details about * all the objects and using {@link #populateS3ObjectMap(String, S3Object[])} to product an object/key * map. * * @see #buildDiscrepancyLists(Map, Map) * @see #buildFileMap(File, String, boolean) * * @param s3Service * @param bucket * @param targetPath * @param s3ObjectsIncomplete * @return * mapping of keys/S3Objects * @throws S3ServiceException */ public static Map buildS3ObjectMap(S3Service s3Service, S3Bucket bucket, String targetPath, S3Object[] s3ObjectsIncomplete, S3ServiceEventListener s3ServiceEventListener) throws S3ServiceException { // Retrieve the complete information about all objects listed via GetObjectsHeads. final ArrayList s3ObjectsCompleteList = new ArrayList(s3ObjectsIncomplete.length); final S3ServiceException s3ServiceExceptions[] = new S3ServiceException[1]; S3ServiceMulti s3ServiceMulti = new S3ServiceMulti(s3Service, new S3ServiceEventAdaptor() { public void s3ServiceEventPerformed(GetObjectHeadsEvent event) { if (GetObjectHeadsEvent.EVENT_IN_PROGRESS == event.getEventCode()) { S3Object[] finishedObjects = event.getCompletedObjects(); if (finishedObjects.length > 0) { s3ObjectsCompleteList.addAll(Arrays.asList(finishedObjects)); } } else if (GetObjectHeadsEvent.EVENT_ERROR == event.getEventCode()) { s3ServiceExceptions[0] = new S3ServiceException( "Failed to retrieve detailed information about all S3 objects", event.getErrorCause()); } } }); if (s3ServiceEventListener != null) { s3ServiceMulti.addServiceEventListener(s3ServiceEventListener); } s3ServiceMulti.getObjectsHeads(bucket, s3ObjectsIncomplete); if (s3ServiceExceptions[0] != null) { throw s3ServiceExceptions[0]; } S3Object[] s3Objects = (S3Object[]) s3ObjectsCompleteList .toArray(new S3Object[s3ObjectsCompleteList.size()]); return populateS3ObjectMap(targetPath, s3Objects); } /** * Builds a map of key/object pairs each object is associated with a key based on its location * in the S3 target path. * * @param targetPath * @param s3Objects * @return * a map of key/S3Object pairs. */ public static Map populateS3ObjectMap(String targetPath, S3Object[] s3Objects) { HashMap map = new HashMap(); for (int i = 0; i < s3Objects.length; i++) { String relativeKey = s3Objects[i].getKey(); if (targetPath.length() > 0) { relativeKey = relativeKey.substring(targetPath.length()); int slashIndex = relativeKey.indexOf(Constants.FILE_PATH_DELIM); if (slashIndex >= 0) { relativeKey = relativeKey.substring(slashIndex + 1, relativeKey.length()); } else { // This relative key is part of a prefix search, the key does not point to a // real S3 object. relativeKey = ""; } } if (relativeKey.length() > 0) { map.put(relativeKey, s3Objects[i]); } } return map; } /** * Compares the contents of a directory on the local file system with the contents of an * S3 resource. This comparison is performed on a map of files and a map of S3 objects previously * generated using other methods in this class. * * @param filesMap * a map of keys/Files built using the method {@link #buildFileMap(File, String, boolean)} * @param s3ObjectsMap * a map of keys/S3Objects built using the method * {@link #buildS3ObjectMap(S3Service, S3Bucket, String, S3ServiceEventListener)} * @return * an object containing the results of the file comparison. * * @throws NoSuchAlgorithmException * @throws FileNotFoundException * @throws IOException * @throws ParseException */ public static FileComparerResults buildDiscrepancyLists(Map filesMap, Map s3ObjectsMap) throws NoSuchAlgorithmException, FileNotFoundException, IOException, ParseException { return buildDiscrepancyLists(filesMap, s3ObjectsMap, null); } /** * Compares the contents of a directory on the local file system with the contents of an * S3 resource. This comparison is performed on a map of files and a map of S3 objects previously * generated using other methods in this class. * * @param filesMap * a map of keys/Files built using the method {@link #buildFileMap(File, String, boolean)} * @param s3ObjectsMap * a map of keys/S3Objects built using the method * {@link #buildS3ObjectMap(S3Service, S3Bucket, String, S3ServiceEventListener)} * @param progressWatcher * watches the progress of file hash generation. * @return * an object containing the results of the file comparison. * * @throws NoSuchAlgorithmException * @throws FileNotFoundException * @throws IOException * @throws ParseException */ public static FileComparerResults buildDiscrepancyLists(Map filesMap, Map s3ObjectsMap, BytesProgressWatcher progressWatcher) throws NoSuchAlgorithmException, FileNotFoundException, IOException, ParseException { List onlyOnServerKeys = new ArrayList(); List updatedOnServerKeys = new ArrayList(); List updatedOnClientKeys = new ArrayList(); List alreadySynchronisedKeys = new ArrayList(); List onlyOnClientKeys = new ArrayList(); // Check files on server against local client files. Iterator s3ObjectsMapIter = s3ObjectsMap.entrySet().iterator(); while (s3ObjectsMapIter.hasNext()) { Map.Entry entry = (Map.Entry) s3ObjectsMapIter.next(); String keyPath = (String) entry.getKey(); S3Object s3Object = (S3Object) entry.getValue(); // Check whether local file is already on server if (filesMap.containsKey(keyPath)) { // File has been backed up in the past, is it still up-to-date? File file = (File) filesMap.get(keyPath); if (file.isDirectory()) { // We don't care about directory date changes, as long as it's present. alreadySynchronisedKeys.add(keyPath); } else { // Compare file hashes. boolean useMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.use-md5-files", false); boolean generateMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.generate-md5-files", false); byte[] computedHash = null; // Check whether a pre-computed MD5 hash file is available File computedHashFile = new File(file.getPath() + ".md5"); if (useMd5Files && computedHashFile.canRead() && computedHashFile.lastModified() > file.lastModified()) { try { // A pre-computed MD5 hash file is available, try to read this hash value BufferedReader br = new BufferedReader(new FileReader(computedHashFile)); - computedHash = ServiceUtils.fromHex(br.readLine().split("\b")[0]); + computedHash = ServiceUtils.fromHex(br.readLine().split("\\s")[0]); br.close(); } catch (Exception e) { log.warn("Unable to read hash from computed MD5 file", e); } } if (computedHash == null) { // A pre-computed hash file was not available, or could not be read. // Calculate the hash value anew. InputStream hashInputStream = null; if (progressWatcher != null) { hashInputStream = new ProgressMonitoredInputStream( // Report on MD5 hash progress. new FileInputStream(file), progressWatcher); } else { hashInputStream = new FileInputStream(file); } computedHash = ServiceUtils.computeMD5Hash(hashInputStream); } String fileHashAsBase64 = ServiceUtils.toBase64(computedHash); if (generateMd5Files && !file.getName().endsWith(".md5") && (!computedHashFile.exists() || computedHashFile.lastModified() < file.lastModified())) { // Create or update a pre-computed MD5 hash file. try { FileWriter fw = new FileWriter(computedHashFile); fw.write(ServiceUtils.toHex(computedHash)); fw.close(); } catch (Exception e) { log.warn("Unable to write computed MD5 hash to a file", e); } } // Get the S3 object's Base64 hash. String objectHash = null; if (s3Object.containsMetadata(S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5)) { // Use the object's *original* hash, as it is an encoded version of a local file. objectHash = (String) s3Object.getMetadata( S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5); log.debug("Object in S3 is encoded, using the object's original hash value for: " + s3Object.getKey()); } else { // The object wasn't altered when uploaded, so use its current hash. objectHash = s3Object.getMd5HashAsBase64(); } if (fileHashAsBase64.equals(objectHash)) { // Hashes match so file is already synchronised. alreadySynchronisedKeys.add(keyPath); } else { // File is out-of-synch. Check which version has the latest date. Date s3ObjectLastModified = null; String metadataLocalFileDate = (String) s3Object.getMetadata( Constants.METADATA_JETS3T_LOCAL_FILE_DATE); if (metadataLocalFileDate == null) { // This is risky as local file times and S3 times don't match! log.warn("Using S3 last modified date as file date. This is not reliable " + "as the time according to S3 can differ from your local system time. " + "Please use the metadata item " + Constants.METADATA_JETS3T_LOCAL_FILE_DATE); s3ObjectLastModified = s3Object.getLastModifiedDate(); } else { s3ObjectLastModified = ServiceUtils .parseIso8601Date(metadataLocalFileDate); } if (s3ObjectLastModified.getTime() > file.lastModified()) { updatedOnServerKeys.add(keyPath); } else if (s3ObjectLastModified.getTime() < file.lastModified()) { updatedOnClientKeys.add(keyPath); } else { // Dates match exactly but the hash doesn't. Shouldn't ever happen! throw new IOException("Backed-up S3Object " + s3Object.getKey() + " and local file " + file.getName() + " have the same date but different hash values. " + "This shouldn't happen!"); } } } } else { // File is not in local file system, so it's only on the S3 // server. onlyOnServerKeys.add(keyPath); } } // Any local files not already put into another list only exist locally. onlyOnClientKeys.addAll(filesMap.keySet()); onlyOnClientKeys.removeAll(updatedOnClientKeys); onlyOnClientKeys.removeAll(alreadySynchronisedKeys); onlyOnClientKeys.removeAll(updatedOnServerKeys); return new FileComparerResults(onlyOnServerKeys, updatedOnServerKeys, updatedOnClientKeys, onlyOnClientKeys, alreadySynchronisedKeys); } }
true
true
public static FileComparerResults buildDiscrepancyLists(Map filesMap, Map s3ObjectsMap, BytesProgressWatcher progressWatcher) throws NoSuchAlgorithmException, FileNotFoundException, IOException, ParseException { List onlyOnServerKeys = new ArrayList(); List updatedOnServerKeys = new ArrayList(); List updatedOnClientKeys = new ArrayList(); List alreadySynchronisedKeys = new ArrayList(); List onlyOnClientKeys = new ArrayList(); // Check files on server against local client files. Iterator s3ObjectsMapIter = s3ObjectsMap.entrySet().iterator(); while (s3ObjectsMapIter.hasNext()) { Map.Entry entry = (Map.Entry) s3ObjectsMapIter.next(); String keyPath = (String) entry.getKey(); S3Object s3Object = (S3Object) entry.getValue(); // Check whether local file is already on server if (filesMap.containsKey(keyPath)) { // File has been backed up in the past, is it still up-to-date? File file = (File) filesMap.get(keyPath); if (file.isDirectory()) { // We don't care about directory date changes, as long as it's present. alreadySynchronisedKeys.add(keyPath); } else { // Compare file hashes. boolean useMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.use-md5-files", false); boolean generateMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.generate-md5-files", false); byte[] computedHash = null; // Check whether a pre-computed MD5 hash file is available File computedHashFile = new File(file.getPath() + ".md5"); if (useMd5Files && computedHashFile.canRead() && computedHashFile.lastModified() > file.lastModified()) { try { // A pre-computed MD5 hash file is available, try to read this hash value BufferedReader br = new BufferedReader(new FileReader(computedHashFile)); computedHash = ServiceUtils.fromHex(br.readLine().split("\b")[0]); br.close(); } catch (Exception e) { log.warn("Unable to read hash from computed MD5 file", e); } } if (computedHash == null) { // A pre-computed hash file was not available, or could not be read. // Calculate the hash value anew. InputStream hashInputStream = null; if (progressWatcher != null) { hashInputStream = new ProgressMonitoredInputStream( // Report on MD5 hash progress. new FileInputStream(file), progressWatcher); } else { hashInputStream = new FileInputStream(file); } computedHash = ServiceUtils.computeMD5Hash(hashInputStream); } String fileHashAsBase64 = ServiceUtils.toBase64(computedHash); if (generateMd5Files && !file.getName().endsWith(".md5") && (!computedHashFile.exists() || computedHashFile.lastModified() < file.lastModified())) { // Create or update a pre-computed MD5 hash file. try { FileWriter fw = new FileWriter(computedHashFile); fw.write(ServiceUtils.toHex(computedHash)); fw.close(); } catch (Exception e) { log.warn("Unable to write computed MD5 hash to a file", e); } } // Get the S3 object's Base64 hash. String objectHash = null; if (s3Object.containsMetadata(S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5)) { // Use the object's *original* hash, as it is an encoded version of a local file. objectHash = (String) s3Object.getMetadata( S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5); log.debug("Object in S3 is encoded, using the object's original hash value for: " + s3Object.getKey()); } else { // The object wasn't altered when uploaded, so use its current hash. objectHash = s3Object.getMd5HashAsBase64(); } if (fileHashAsBase64.equals(objectHash)) { // Hashes match so file is already synchronised. alreadySynchronisedKeys.add(keyPath); } else { // File is out-of-synch. Check which version has the latest date. Date s3ObjectLastModified = null; String metadataLocalFileDate = (String) s3Object.getMetadata( Constants.METADATA_JETS3T_LOCAL_FILE_DATE); if (metadataLocalFileDate == null) { // This is risky as local file times and S3 times don't match! log.warn("Using S3 last modified date as file date. This is not reliable " + "as the time according to S3 can differ from your local system time. " + "Please use the metadata item " + Constants.METADATA_JETS3T_LOCAL_FILE_DATE); s3ObjectLastModified = s3Object.getLastModifiedDate(); } else { s3ObjectLastModified = ServiceUtils .parseIso8601Date(metadataLocalFileDate); } if (s3ObjectLastModified.getTime() > file.lastModified()) { updatedOnServerKeys.add(keyPath); } else if (s3ObjectLastModified.getTime() < file.lastModified()) { updatedOnClientKeys.add(keyPath); } else { // Dates match exactly but the hash doesn't. Shouldn't ever happen! throw new IOException("Backed-up S3Object " + s3Object.getKey() + " and local file " + file.getName() + " have the same date but different hash values. " + "This shouldn't happen!"); } } } } else { // File is not in local file system, so it's only on the S3 // server. onlyOnServerKeys.add(keyPath); } } // Any local files not already put into another list only exist locally. onlyOnClientKeys.addAll(filesMap.keySet()); onlyOnClientKeys.removeAll(updatedOnClientKeys); onlyOnClientKeys.removeAll(alreadySynchronisedKeys); onlyOnClientKeys.removeAll(updatedOnServerKeys); return new FileComparerResults(onlyOnServerKeys, updatedOnServerKeys, updatedOnClientKeys, onlyOnClientKeys, alreadySynchronisedKeys); }
public static FileComparerResults buildDiscrepancyLists(Map filesMap, Map s3ObjectsMap, BytesProgressWatcher progressWatcher) throws NoSuchAlgorithmException, FileNotFoundException, IOException, ParseException { List onlyOnServerKeys = new ArrayList(); List updatedOnServerKeys = new ArrayList(); List updatedOnClientKeys = new ArrayList(); List alreadySynchronisedKeys = new ArrayList(); List onlyOnClientKeys = new ArrayList(); // Check files on server against local client files. Iterator s3ObjectsMapIter = s3ObjectsMap.entrySet().iterator(); while (s3ObjectsMapIter.hasNext()) { Map.Entry entry = (Map.Entry) s3ObjectsMapIter.next(); String keyPath = (String) entry.getKey(); S3Object s3Object = (S3Object) entry.getValue(); // Check whether local file is already on server if (filesMap.containsKey(keyPath)) { // File has been backed up in the past, is it still up-to-date? File file = (File) filesMap.get(keyPath); if (file.isDirectory()) { // We don't care about directory date changes, as long as it's present. alreadySynchronisedKeys.add(keyPath); } else { // Compare file hashes. boolean useMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.use-md5-files", false); boolean generateMd5Files = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME) .getBoolProperty("filecomparer.generate-md5-files", false); byte[] computedHash = null; // Check whether a pre-computed MD5 hash file is available File computedHashFile = new File(file.getPath() + ".md5"); if (useMd5Files && computedHashFile.canRead() && computedHashFile.lastModified() > file.lastModified()) { try { // A pre-computed MD5 hash file is available, try to read this hash value BufferedReader br = new BufferedReader(new FileReader(computedHashFile)); computedHash = ServiceUtils.fromHex(br.readLine().split("\\s")[0]); br.close(); } catch (Exception e) { log.warn("Unable to read hash from computed MD5 file", e); } } if (computedHash == null) { // A pre-computed hash file was not available, or could not be read. // Calculate the hash value anew. InputStream hashInputStream = null; if (progressWatcher != null) { hashInputStream = new ProgressMonitoredInputStream( // Report on MD5 hash progress. new FileInputStream(file), progressWatcher); } else { hashInputStream = new FileInputStream(file); } computedHash = ServiceUtils.computeMD5Hash(hashInputStream); } String fileHashAsBase64 = ServiceUtils.toBase64(computedHash); if (generateMd5Files && !file.getName().endsWith(".md5") && (!computedHashFile.exists() || computedHashFile.lastModified() < file.lastModified())) { // Create or update a pre-computed MD5 hash file. try { FileWriter fw = new FileWriter(computedHashFile); fw.write(ServiceUtils.toHex(computedHash)); fw.close(); } catch (Exception e) { log.warn("Unable to write computed MD5 hash to a file", e); } } // Get the S3 object's Base64 hash. String objectHash = null; if (s3Object.containsMetadata(S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5)) { // Use the object's *original* hash, as it is an encoded version of a local file. objectHash = (String) s3Object.getMetadata( S3Object.METADATA_HEADER_ORIGINAL_HASH_MD5); log.debug("Object in S3 is encoded, using the object's original hash value for: " + s3Object.getKey()); } else { // The object wasn't altered when uploaded, so use its current hash. objectHash = s3Object.getMd5HashAsBase64(); } if (fileHashAsBase64.equals(objectHash)) { // Hashes match so file is already synchronised. alreadySynchronisedKeys.add(keyPath); } else { // File is out-of-synch. Check which version has the latest date. Date s3ObjectLastModified = null; String metadataLocalFileDate = (String) s3Object.getMetadata( Constants.METADATA_JETS3T_LOCAL_FILE_DATE); if (metadataLocalFileDate == null) { // This is risky as local file times and S3 times don't match! log.warn("Using S3 last modified date as file date. This is not reliable " + "as the time according to S3 can differ from your local system time. " + "Please use the metadata item " + Constants.METADATA_JETS3T_LOCAL_FILE_DATE); s3ObjectLastModified = s3Object.getLastModifiedDate(); } else { s3ObjectLastModified = ServiceUtils .parseIso8601Date(metadataLocalFileDate); } if (s3ObjectLastModified.getTime() > file.lastModified()) { updatedOnServerKeys.add(keyPath); } else if (s3ObjectLastModified.getTime() < file.lastModified()) { updatedOnClientKeys.add(keyPath); } else { // Dates match exactly but the hash doesn't. Shouldn't ever happen! throw new IOException("Backed-up S3Object " + s3Object.getKey() + " and local file " + file.getName() + " have the same date but different hash values. " + "This shouldn't happen!"); } } } } else { // File is not in local file system, so it's only on the S3 // server. onlyOnServerKeys.add(keyPath); } } // Any local files not already put into another list only exist locally. onlyOnClientKeys.addAll(filesMap.keySet()); onlyOnClientKeys.removeAll(updatedOnClientKeys); onlyOnClientKeys.removeAll(alreadySynchronisedKeys); onlyOnClientKeys.removeAll(updatedOnServerKeys); return new FileComparerResults(onlyOnServerKeys, updatedOnServerKeys, updatedOnClientKeys, onlyOnClientKeys, alreadySynchronisedKeys); }
diff --git a/src/test/java/de/banapple/confluence/GridUrlCodecTest.java b/src/test/java/de/banapple/confluence/GridUrlCodecTest.java index 514bf66..76d3ad0 100644 --- a/src/test/java/de/banapple/confluence/GridUrlCodecTest.java +++ b/src/test/java/de/banapple/confluence/GridUrlCodecTest.java @@ -1,34 +1,34 @@ package de.banapple.confluence; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; public class GridUrlCodecTest extends TestCase { private GridUrlCodec codec; public void setUp() { BasicConfigurator.configure(); codec = new DefaultGridUrlCodec(); } public void testCompressDecompress() { String text = "+----------+\n"+ "|Hallo Welt|\n"+ "+----------+\n"; System.out.println(text); String compressedText = codec.encode(text); System.out.println(compressedText); String decoded = codec.decode(compressedText); System.out.println(decoded); - Assert.assertEquals(text, decoded); + Assert.assertEquals(compressedText, decoded); } }
true
true
public void testCompressDecompress() { String text = "+----------+\n"+ "|Hallo Welt|\n"+ "+----------+\n"; System.out.println(text); String compressedText = codec.encode(text); System.out.println(compressedText); String decoded = codec.decode(compressedText); System.out.println(decoded); Assert.assertEquals(text, decoded); }
public void testCompressDecompress() { String text = "+----------+\n"+ "|Hallo Welt|\n"+ "+----------+\n"; System.out.println(text); String compressedText = codec.encode(text); System.out.println(compressedText); String decoded = codec.decode(compressedText); System.out.println(decoded); Assert.assertEquals(compressedText, decoded); }
diff --git a/freeplane/src/org/freeplane/features/styles/LogicalStyleController.java b/freeplane/src/org/freeplane/features/styles/LogicalStyleController.java index 6ecb8296f..127d279b7 100644 --- a/freeplane/src/org/freeplane/features/styles/LogicalStyleController.java +++ b/freeplane/src/org/freeplane/features/styles/LogicalStyleController.java @@ -1,377 +1,378 @@ /* * Freeplane - mind map editor * Copyright (C) 2009 Dimitry * * This file author is Dimitry * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.styles; import java.awt.Component; import java.awt.EventQueue; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.freeplane.core.extension.IExtension; import org.freeplane.core.io.IAttributeHandler; import org.freeplane.core.io.IAttributeWriter; import org.freeplane.core.io.ITreeWriter; import org.freeplane.core.io.ReadManager; import org.freeplane.core.io.WriteManager; import org.freeplane.core.resources.NamedObject; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.undo.IActor; import org.freeplane.core.util.HtmlUtils; import org.freeplane.core.util.TextUtils; import org.freeplane.features.filter.condition.ASelectableCondition; import org.freeplane.features.map.IMapChangeListener; import org.freeplane.features.map.INodeChangeListener; import org.freeplane.features.map.ITooltipProvider; import org.freeplane.features.map.MapChangeEvent; import org.freeplane.features.map.MapController; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.NodeBuilder; import org.freeplane.features.map.NodeChangeEvent; import org.freeplane.features.map.NodeModel; import org.freeplane.features.mode.CombinedPropertyChain; import org.freeplane.features.mode.Controller; import org.freeplane.features.mode.IPropertyHandler; import org.freeplane.features.mode.ModeController; import org.freeplane.features.styles.ConditionalStyleModel.Item; /** * @author Dimitry Polivaev * 28.09.2009 */ public class LogicalStyleController implements IExtension { // final private ModeController modeController; private static final int STYLE_TOOLTIP = 0; private WeakReference<NodeModel> cachedNode; private Collection<IStyle> cachedStyle; final private CombinedPropertyChain<Collection<IStyle>, NodeModel> styleHandlers; public LogicalStyleController(ModeController modeController) { // this.modeController = modeController; styleHandlers = new CombinedPropertyChain<Collection<IStyle>, NodeModel>(false); createBuilder(); registerChangeListener(); addStyleGetter(IPropertyHandler.NODE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); add(node, styleModel, currentValue, new StyleNode(node)); return currentValue; } }); addStyleGetter(IPropertyHandler.STYLE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); Collection<IStyle> condStyles = styleModel.getConditionalStyleModel().getStyles(node); addAll(node, styleModel, currentValue, condStyles); return currentValue; } }); addStyleGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { add(node, currentValue, MapStyleModel.DEFAULT_STYLE); return currentValue; } }); modeController.addToolTipProvider(STYLE_TOOLTIP, new ITooltipProvider() { public String getTooltip(ModeController modeController, NodeModel node, Component view) { if(!ResourceController.getResourceController().getBooleanProperty("show_styles_in_tooltip")) return null; final Collection<IStyle> styles = getStyles(node); - styles.remove(styles.iterator().next()); + if(styles.size() > 0) + styles.remove(styles.iterator().next()); final String label = TextUtils.getText("node_styles"); return HtmlUtils.plainToHTML(label + ": " + getStyleNames(styles, ", ")); } }); } protected Collection<IStyle> getResursively(NodeModel node, Collection<IStyle> collection) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); Collection<IStyle> set = new LinkedHashSet<IStyle>(); addAll(node, styleModel, set, collection); return set; } protected void addAll(NodeModel node, MapStyleModel styleModel, Collection<IStyle> currentValue, Collection<IStyle> collection) { for(IStyle styleKey : collection){ add(node, styleModel, currentValue, styleKey); } } public void add(NodeModel node, Collection<IStyle> currentValue, IStyle style) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); add(node, styleModel, currentValue, style); } protected void add(NodeModel node, MapStyleModel styleModel, Collection<IStyle> currentValue, IStyle styleKey) { if(!currentValue.add(styleKey)){ return; } final NodeModel styleNode = styleModel.getStyleNode(styleKey); if (styleNode == null) { return; } if(styleKey instanceof StyleNode){ IStyle style = LogicalStyleModel.getStyle(styleNode); if(style != null){ add(node, styleModel, currentValue, style); } } final ConditionalStyleModel conditionalStyleModel = (ConditionalStyleModel) styleNode.getExtension(ConditionalStyleModel.class); if(conditionalStyleModel == null) return; addAll(node, styleModel, currentValue, conditionalStyleModel.getStyles(node)); } private void registerChangeListener() { ModeController modeController = Controller.getCurrentModeController(); final MapController mapController = modeController.getMapController(); mapController.addMapChangeListener(new IMapChangeListener() { public void onPreNodeMoved(NodeModel oldParent, int oldIndex, NodeModel newParent, NodeModel child, int newIndex) { clearCache(); } public void onPreNodeDelete(NodeModel oldParent, NodeModel selectedNode, int index) { clearCache(); } public void onNodeMoved(NodeModel oldParent, int oldIndex, NodeModel newParent, NodeModel child, int newIndex) { clearCache(); } public void onNodeInserted(NodeModel parent, NodeModel child, int newIndex) { clearCache(); } public void onNodeDeleted(NodeModel parent, NodeModel child, int index) { clearCache(); } public void mapChanged(MapChangeEvent event) { clearCache(); } }); mapController.addNodeChangeListener(new INodeChangeListener() { public void nodeChanged(NodeChangeEvent event) { clearCache(); } }); } private void createBuilder() { ModeController modeController = Controller.getCurrentModeController(); final MapController mapController = modeController.getMapController(); final ReadManager readManager = mapController.getReadManager(); readManager.addAttributeHandler(NodeBuilder.XML_NODE, "STYLE_REF", new IAttributeHandler() { public void setAttribute(final Object node, final String value) { final LogicalStyleModel extension = LogicalStyleModel.createExtension((NodeModel) node); extension.setStyle(StyleFactory.create(value)); } }); readManager.addAttributeHandler(NodeBuilder.XML_NODE, "LOCALIZED_STYLE_REF", new IAttributeHandler() { public void setAttribute(final Object node, final String value) { final LogicalStyleModel extension = LogicalStyleModel.createExtension((NodeModel) node); extension.setStyle(StyleFactory.create(NamedObject.format(value))); } }); final WriteManager writeManager = mapController.getWriteManager(); writeManager.addAttributeWriter(NodeBuilder.XML_NODE, new IAttributeWriter() { public void writeAttributes(final ITreeWriter writer, final Object node, final String tag) { final LogicalStyleModel extension = LogicalStyleModel.getExtension((NodeModel) node); if (extension == null) { return; } final IStyle style = extension.getStyle(); if (style == null) { return; } final String value = StyleNamedObject.toKeyString(style); if (style instanceof StyleNamedObject) { writer.addAttribute("LOCALIZED_STYLE_REF", value); } else { writer.addAttribute("STYLE_REF", value); } } }); } public static void install( final LogicalStyleController logicalStyleController) { final ModeController modeController = Controller.getCurrentModeController(); modeController.addExtension(LogicalStyleController.class, logicalStyleController); } public static LogicalStyleController getController() { final ModeController modeController = Controller.getCurrentModeController(); return getController(modeController); } public static LogicalStyleController getController(ModeController modeController) { return (LogicalStyleController) modeController.getExtension(LogicalStyleController.class); } public void refreshMap(final MapModel map) { final IActor actor = new IActor() { public void undo() { refreshMapLater(map); } public String getDescription() { return "refreshMap"; } public void act() { refreshMapLater(map); } }; Controller.getCurrentModeController().execute(actor, map); } private static Map<MapModel, Integer> mapsToRefresh = new HashMap<MapModel, Integer>(); private void refreshMapLater(final MapModel map) { final Integer count = mapsToRefresh.get(map); if (count == null) { mapsToRefresh.put(map, 0); } else { mapsToRefresh.put(map, count + 1); } EventQueue.invokeLater(new Runnable() { public void run() { final Integer count = mapsToRefresh.get(map); if (count > 0) { mapsToRefresh.put(map, count - 1); return; } mapsToRefresh.remove(map); final MapStyleModel extension = MapStyleModel.getExtension(map); extension.refreshStyles(); Controller.getCurrentModeController().getMapController().fireMapChanged( new MapChangeEvent(this, map, MapStyle.MAP_STYLES, null, null)); } }); } public IStyle getFirstStyle(final NodeModel node){ final Collection<IStyle> styles = getStyles(node); boolean found = false; for(IStyle style:styles){ if(found){ return style; } if((style instanceof StyleNode)){ found = true; } } return null; } public Collection<IStyle> getStyles(final NodeModel node) { if(cachedNode != null && node.equals(cachedNode.get())){ return cachedStyle; } cachedStyle = styleHandlers.getProperty(node, new LinkedHashSet<IStyle>()); cachedNode = new WeakReference<NodeModel>(node); return cachedStyle; } public void moveConditionalStyleDown(final ConditionalStyleModel conditionalStyleModel, int index) { conditionalStyleModel.moveDown(index); } public void moveConditionalStyleUp(final ConditionalStyleModel conditionalStyleModel, int index) { conditionalStyleModel.moveUp(index); } public void addConditionalStyle(final ConditionalStyleModel conditionalStyleModel, boolean isActive, ASelectableCondition condition, IStyle style, boolean isLast) { conditionalStyleModel.addCondition(isActive, condition, style, isLast); } public void insertConditionalStyle(final ConditionalStyleModel conditionalStyleModel, int index, boolean isActive, ASelectableCondition condition, IStyle style, boolean isLast) { conditionalStyleModel.insertCondition(index, isActive, condition, style, isLast); } public Item removeConditionalStyle(final ConditionalStyleModel conditionalStyleModel, int index) { return conditionalStyleModel.removeCondition(index); } private void clearCache() { cachedStyle = null; cachedNode = null; } public IPropertyHandler<Collection<IStyle>, NodeModel> addStyleGetter( final Integer key, final IPropertyHandler<Collection<IStyle>, NodeModel> getter) { return styleHandlers.addGetter(key, getter); } public IPropertyHandler<Collection<IStyle>, NodeModel> removeStyleGetter( final Integer key, final IPropertyHandler<Collection<IStyle>, NodeModel> getter) { return styleHandlers.addGetter(key, getter); } public String getStyleNames(final Collection<IStyle> styles, String separator) { StringBuilder sb = new StringBuilder(); int i = 0; for(IStyle style :styles){ if(i > 0) sb.append(separator); sb.append(style.toString()); i++; } return sb.toString(); } public Collection<IStyle> getConditionalMapStyles(final NodeModel node) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); Collection<IStyle> condStyles = styleModel.getConditionalStyleModel().getStyles(node); return getResursively(node, condStyles); } public Collection<IStyle> getConditionalNodeStyles(final NodeModel node) { final Collection<IStyle> condStyles = new LinkedHashSet<IStyle>(); IStyle style = LogicalStyleModel.getStyle(node); if(style != null){ condStyles.add(style); } final ConditionalStyleModel conditionalStyleModel = (ConditionalStyleModel) node.getExtension(ConditionalStyleModel.class); if(conditionalStyleModel != null) condStyles.addAll(conditionalStyleModel.getStyles(node)); final Collection<IStyle> all = getResursively(node, condStyles); if(style != null){ all.remove(style); } return all; } public String getNodeStyleNames(NodeModel node, String separator) { return getStyleNames(getConditionalNodeStyles(node), separator); } public String getMapStyleNames(NodeModel node, String separator) { return getStyleNames(getConditionalMapStyles(node), separator); } }
true
true
public LogicalStyleController(ModeController modeController) { // this.modeController = modeController; styleHandlers = new CombinedPropertyChain<Collection<IStyle>, NodeModel>(false); createBuilder(); registerChangeListener(); addStyleGetter(IPropertyHandler.NODE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); add(node, styleModel, currentValue, new StyleNode(node)); return currentValue; } }); addStyleGetter(IPropertyHandler.STYLE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); Collection<IStyle> condStyles = styleModel.getConditionalStyleModel().getStyles(node); addAll(node, styleModel, currentValue, condStyles); return currentValue; } }); addStyleGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { add(node, currentValue, MapStyleModel.DEFAULT_STYLE); return currentValue; } }); modeController.addToolTipProvider(STYLE_TOOLTIP, new ITooltipProvider() { public String getTooltip(ModeController modeController, NodeModel node, Component view) { if(!ResourceController.getResourceController().getBooleanProperty("show_styles_in_tooltip")) return null; final Collection<IStyle> styles = getStyles(node); styles.remove(styles.iterator().next()); final String label = TextUtils.getText("node_styles"); return HtmlUtils.plainToHTML(label + ": " + getStyleNames(styles, ", ")); } }); }
public LogicalStyleController(ModeController modeController) { // this.modeController = modeController; styleHandlers = new CombinedPropertyChain<Collection<IStyle>, NodeModel>(false); createBuilder(); registerChangeListener(); addStyleGetter(IPropertyHandler.NODE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); add(node, styleModel, currentValue, new StyleNode(node)); return currentValue; } }); addStyleGetter(IPropertyHandler.STYLE, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { final MapStyleModel styleModel = MapStyleModel.getExtension(node.getMap()); Collection<IStyle> condStyles = styleModel.getConditionalStyleModel().getStyles(node); addAll(node, styleModel, currentValue, condStyles); return currentValue; } }); addStyleGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<Collection<IStyle>, NodeModel>() { public Collection<IStyle> getProperty(NodeModel node, Collection<IStyle> currentValue) { add(node, currentValue, MapStyleModel.DEFAULT_STYLE); return currentValue; } }); modeController.addToolTipProvider(STYLE_TOOLTIP, new ITooltipProvider() { public String getTooltip(ModeController modeController, NodeModel node, Component view) { if(!ResourceController.getResourceController().getBooleanProperty("show_styles_in_tooltip")) return null; final Collection<IStyle> styles = getStyles(node); if(styles.size() > 0) styles.remove(styles.iterator().next()); final String label = TextUtils.getText("node_styles"); return HtmlUtils.plainToHTML(label + ": " + getStyleNames(styles, ", ")); } }); }
diff --git a/lorian/graph/GraphFrame.java b/lorian/graph/GraphFrame.java index afc570e..8073625 100644 --- a/lorian/graph/GraphFrame.java +++ b/lorian/graph/GraphFrame.java @@ -1,562 +1,568 @@ package lorian.graph; import lorian.graph.function.*; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Label; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Spring; import javax.swing.SpringLayout; public class GraphFrame extends JPanel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = -741311884013992607L; private List<Function> functions; private List<VisualPoint> vpoints; private List<Point> vmovablepoints; private boolean vpointsVisible = false; private Image pointimg, movablepointimg; private int MovingVPointIndex = -1; private int MovingPointIndex = -1; private Point MouseStart; private WindowSettings settings; private int YaxisX, XaxisY; Dimension size; public boolean windowerror = false; private JPanel CalcPanel; private boolean CalcPanelVisible = false; private boolean clearOnlyCorner = false; private int FillFunctionIndex = -1; private double FillLowX = 0, FillUpX = 0; GraphFrame(List<Function> functions, WindowSettings settings, Dimension size) { super(); this.size = size; this.functions = functions; this.settings = settings; this.setPreferredSize(size); this.setBackground(Color.WHITE); this.setOpaque(false); this.addMouseListener(this); this.addMouseMotionListener(this); vpoints = new ArrayList<VisualPoint>(); vmovablepoints = new ArrayList<Point>(); try { pointimg = ImageIO.read(getClass().getResource("/res/point.png")).getScaledInstance(25, 25, 0); } catch (IOException e) { e.printStackTrace(); } try { movablepointimg = ImageIO.read(getClass().getResource("/res/movablepoint.png")).getScaledInstance(25, 25, 0); } catch (IOException e) { e.printStackTrace(); } InitCalcPanel(); CalculateAxes(); } private void InitCalcPanel() { CalcPanel = new JPanel(); SpringLayout layout = new SpringLayout(); this.setLayout(layout); CalcPanel.setPreferredSize(new Dimension(275, 200)); CalcPanel.setVisible(CalcPanelVisible); this.add(CalcPanel); SpringLayout.Constraints cons = layout.getConstraints(CalcPanel); //cons.setX(Spring.constant((int) (size.getWidth() - CalcPanel.getPreferredSize().getWidth()))); cons.setX(Spring.constant(0)); cons.setY(Spring.constant((int) (size.getHeight() - CalcPanel.getPreferredSize().getHeight()))); } private void CalculateAxes() { YaxisX = (int) (size.getWidth() * ((double) -settings.getXmin()) / ((double) (settings.getXmax() - settings.getXmin()))) - 1; XaxisY = (int) size.getHeight() - (int) (size.getHeight() * ((double) -settings.getYmin()) / ((double) (settings.getYmax() - settings.getYmin()))) - 1; windowerror = false; } public void UpdateWindowSettings(WindowSettings settings) { this.settings = settings; if(settings.getXmax() <= settings.getXmin() || settings.getYmax() <= settings.getYmin()) { System.out.println("Error in windowsettings"); windowerror = true; } else windowerror = false; this.repaint(); } private void drawAxes(Graphics g) { int pix; for(long x=settings.getXmin()+1;x<settings.getXmax();x++) { if(x==0) continue; pix = (int) ((x-settings.getXmin()) * (size.getWidth() / (settings.getXmax() - settings.getXmin()))); if(pix==0) continue; g.setColor(Color.BLACK); g.drawLine(pix, XaxisY - 5, pix, XaxisY + 5); } for(long y=settings.getYmin()+1;y<settings.getYmax();y++) { if(y==0) continue; pix = (int) size.getHeight() - (int) ((y-settings.getYmin()) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); if(pix==0) continue; g.setColor(Color.BLACK); g.drawLine(YaxisX - 5, pix, YaxisX + 5, pix); } g.setColor(Color.BLACK); g.drawLine(YaxisX, 0, YaxisX, (int) size.getHeight()); g.drawLine(0, XaxisY, (int) size.getWidth(), XaxisY); } private void drawGrid(Graphics g) { int pix; Color gridColor = new Color(0, 186, 0xff); for(long x=settings.getXmin()+1;x<settings.getXmax();x++) { if(x==0) continue; pix = (int) ((x-settings.getXmin()) * (size.getWidth() / (settings.getXmax() - settings.getXmin()))); if(pix==0) continue; //grid g.setColor(gridColor); g.drawLine(pix, 0, pix, (int) size.getHeight()); } for(long y=settings.getYmin()+1;y<settings.getYmax();y++) { if(y==0) continue; pix = (int) size.getHeight() - (int) ((y-settings.getYmin()) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); if(pix==0) continue; //grid g.setColor(gridColor); g.drawLine(0, pix, (int) size.getWidth(), pix); } } private void drawFunction(Function f, boolean fill, Graphics g) { if(f.isEmpty()) return; g.setColor(f.getColor()); int xpix, ypix; double x,y; double step = ((double) (settings.getXmax() - settings.getXmin())) / size.getWidth(); Point previous = new Point(); boolean WaitForRealNumber = false; for(xpix = -1, x = settings.getXmin(); xpix < (int) size.getWidth(); xpix++, x+=step) { y = f.Calc(x); if(Double.isNaN(y)) { double tmpX = Calculate.FindLastXBeforeNaN(f, x - step); if(!Double.isNaN(tmpX)) { double tmpY = f.Calc(tmpX); ypix = (int) ((settings.getYmax() - tmpY) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); g.drawLine(previous.x, previous.y, xpix, ypix); } previous = null; if(!WaitForRealNumber) { WaitForRealNumber = true; } continue; } else if(WaitForRealNumber) WaitForRealNumber = false; ypix = (int) ((settings.getYmax() - y) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); if(xpix > -1) { if(previous == null) { g.drawRect(xpix, ypix, 1, 1); } else if(Math.abs(xpix - previous.x) < size.getWidth() && Math.abs(ypix - previous.y) < size.getHeight()) { g.drawLine(previous.x, previous.y, xpix, ypix); } if(fill && x >= FillLowX && x <= FillUpX) { g.setColor(Util.lighter(f.getColor())); ((Graphics2D) g).setStroke(new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL)); if(y > 0) { - g.drawLine(xpix, ypix-1, xpix, this.XaxisY); + if(ypix < 0) + g.drawLine(xpix, 0, xpix, this.XaxisY); + else + g.drawLine(xpix, ypix-1, xpix, this.XaxisY); } else if(y < 0) { - g.drawLine(xpix, ypix+1, xpix, this.XaxisY); + if(ypix > size.getHeight()) + g.drawLine(xpix, (int) size.getHeight(), xpix, this.XaxisY); + else + g.drawLine(xpix, ypix+1, xpix, this.XaxisY); } ((Graphics2D) g).setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); g.setColor(f.getColor()); } } if(previous == null) previous = new Point(); previous.setLocation(xpix, ypix); } g.setColor(Color.BLACK); } private void drawCalcPanelBorders(Graphics g) { g.setColor(Color.BLACK); ((Graphics2D) g).setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); //int xoff = (int) (this.getWidth() - CalcPanel.getWidth()) - 1, yoff = (int) (this.getHeight() - CalcPanel.getHeight()) - 2; int xoff = CalcPanel.getWidth() +1, yoff = (int) (this.getHeight() - CalcPanel.getHeight()) - 2; g.drawLine(xoff, yoff, xoff, this.getHeight()); g.drawLine(0, yoff, xoff, yoff); } private String getRightCoordinateString(VisualPoint p) { if(p.isMovable()) return String.format("(%.4f, %.4f)", Util.round(p.getPoint().getX(), 4), Util.round(p.getPoint().getY(), 4)); else return String.format("(%s, %s)", Util.GetString(p.getPoint().getX()), Util.GetString(p.getPoint().getY())); } private void drawVisualPoints(Graphics g) { int x,y; int i=0; for(VisualPoint p: vpoints) { x = (int) (((p.getPoint().getX() - settings.getXmin()) / (settings.getXmax() - settings.getXmin()) * size.getWidth())) - 13; y = (int) size.getHeight() - (int) (((p.getPoint().getY() - settings.getYmin()) / (settings.getYmax() - settings.getYmin()) * size.getHeight())) - 13; if(MovingVPointIndex == i) { vmovablepoints.set(MovingPointIndex, new Point(x, y)); } if(p.isMovable()) { g.drawImage(movablepointimg, x, y, null); } else { g.drawImage(pointimg, x, y, null); } y += 15; x += 25; String text; if(p.coordinatesOn()) { if(p.getLabel().length() > 0) text = p.getLabel() + " " + getRightCoordinateString(p); else text = getRightCoordinateString(p); } else { text = p.getLabel(); } g.setFont(g.getFont().deriveFont(13.0f)); FontMetrics metrics = g.getFontMetrics(g.getFont()); g.setColor(new Color(0xff, 0xff, 0xff, 200)); g.fillRect(x, y - metrics.getHeight(), Util.getStringWidth(metrics, text), metrics.getHeight() + 2); g.setColor(Color.BLACK); g.drawString(text, x, y); i++; } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if(!clearOnlyCorner) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.clearRect(0, 0, (int) this.getWidth(), (int) this.getHeight()); if(windowerror) return; CalculateAxes(); if(settings.gridOn()) drawGrid(g); ((Graphics2D) g).setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); for (int i = 0; i < functions.size(); i++) { drawFunction(functions.get(i), (i == this.FillFunctionIndex), g); } ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); ((Graphics2D) g).setStroke(new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); drawAxes(g); if(vpointsVisible) { drawVisualPoints(g); } if(CalcPanelVisible) drawCalcPanelBorders(g); } } public void SetFillFunctionIndex(int index) { this.FillFunctionIndex = index; } public void SetFillLowerLimit(double lowx) { this.FillLowX = lowx; } public void SetFillUpperLimit(double upx) { this.FillUpX = upx; } public void SetFillFunction(boolean on) { if(!on) this.FillFunctionIndex = -1; } public void Update(List<Function> functions) { this.functions = functions; this.repaint(); } public void Update(int functionindex, Function function) { this.functions.set(functionindex, function); this.repaint(); } public boolean CalcPanelIsVisible() { return CalcPanelVisible; } public void setCalcPanelVisible(boolean calcPanelVisible) { CalcPanelVisible = calcPanelVisible; this.CalcPanel.setVisible(calcPanelVisible); clearOnlyCorner = true; this.repaint(); clearOnlyCorner = false; } public void setCalcPanel(JPanel panel) { CalcPanel.removeAll(); CalcPanel.add(panel); clearOnlyCorner = true; this.paintAll(this.getGraphics()); clearOnlyCorner = false; } public void SetVisualPointsVisible(boolean visible) { this.vpointsVisible = visible; if(visible == false) ClearVisualPoints(); this.repaint(); } public void ClearVisualPoints() { vpoints.clear(); vmovablepoints.clear(); this.repaint(); } public boolean VisualPointsAreVisible() { return this.vpointsVisible; } public void AddVisualPoint(VisualPoint p) { vpoints.add(p); if(p.isMovable()) { System.out.println("Adding movable VisualPoint at index " + (vpoints.size() - 1)); int x = (int) (((p.getPoint().getX() - settings.getXmin()) / (settings.getXmax() - settings.getXmin()) * size.getWidth())) - 13; int y = (int) size.getHeight() - (int) (((p.getPoint().getY() - settings.getYmin()) / (settings.getYmax() - settings.getYmin()) * size.getHeight())) - 13; vmovablepoints.add(new Point(x, y)); } else System.out.println("Adding VisualPoint at index " + (vpoints.size() - 1)); this.repaint(); } public PointXY GetMovableVisualPointLocationByLabel(String label) { for(VisualPoint vp: vpoints) { if(vp.getLabel().equals(label)) return vp.getPoint(); } return null; } public void SetMovableVisualPointLocationByLabel(String label, PointXY newlocation) { int i=0; for(VisualPoint vp: vpoints) { if(vp.getLabel().equals(label)) { vp.setPoint(newlocation); int x = (int) (((vp.getPoint().getX() - settings.getXmin()) / (settings.getXmax() - settings.getXmin()) * size.getWidth())) - 13; int y = (int) size.getHeight() - (int) (((vp.getPoint().getY() - settings.getYmin()) / (settings.getYmax() - settings.getYmin()) * size.getHeight())) - 13; int pointindex = GetMovableVisualPointIndex(i); vmovablepoints.set(pointindex, new Point(x, y)); break; } i++; } this.repaint(); } private int GetMovableVisualPointIndex(int PointIndex) { int icount = 0; //System.out.println(PointIndex); for(int i=0; i < vpoints.size(); i++) { if(vpoints.get(i).isMovable()) { if(icount == PointIndex) { return i; } icount++; } } return -1; } @Override public void mouseDragged(MouseEvent e) { //System.out.println(e.getPoint()); if(this.MovingVPointIndex == -1) return; int deltax = (int) ( MouseStart.getX() -e.getPoint().getX() ); //System.out.println(deltax); //return; double add = (deltax / size.getWidth()) * (settings.getXmax() - settings.getXmin()) * -1 * 0.5; VisualPoint vp = this.vpoints.get(MovingVPointIndex); Point p = this.vmovablepoints.get(MovingPointIndex); if(vp.getFunctionIndex() != -1) { if(vp.getFunctionIndex() < functions.size()) { Function f = this.functions.get(vp.getFunctionIndex()); vp.setPoint(new PointXY(vp.getPoint().getX() + add, f.Calc(vp.getPoint().getX() + add))); int y = (int) size.getHeight() - (int) (((vp.getPoint().getY() - settings.getYmin()) / (settings.getYmax() - settings.getYmin()) * size.getHeight())) - 13; p.setLocation(p.getX() + deltax , y); } else { vp.setPoint(new PointXY(vp.getPoint().getX() + add, vp.getPoint().getY())); p.setLocation(p.getX() + deltax , p.getY()); } } else { vp.setPoint(new PointXY(vp.getPoint().getX() + add, vp.getPoint().getY())); p.setLocation(p.getX() + deltax , p.getY()); } MouseStart = e.getPoint(); this.repaint(); } @Override public void mousePressed(MouseEvent e) { int i=0; MouseStart = e.getPoint(); for(Point p: vmovablepoints) { if(e.getPoint().getX() < p.getX() || e.getPoint().getX() > p.getX() + 25 || e.getPoint().getY() < p.getY() || e.getPoint().getY() > p.getY() + 25) { i++; continue; } MovingPointIndex = i; MovingVPointIndex = GetMovableVisualPointIndex(i); MouseStart = e.getPoint(); return; } } @Override public void mouseMoved(MouseEvent e) { for(Point p: vmovablepoints) { if(e.getPoint().getX() < p.getX() || e.getPoint().getX() > p.getX() + 25 || e.getPoint().getY() < p.getY() || e.getPoint().getY() > p.getY() + 25) { continue; } setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); return; } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { MovingVPointIndex = -1; MovingPointIndex = -1; MouseStart = null; } }
false
true
private void drawFunction(Function f, boolean fill, Graphics g) { if(f.isEmpty()) return; g.setColor(f.getColor()); int xpix, ypix; double x,y; double step = ((double) (settings.getXmax() - settings.getXmin())) / size.getWidth(); Point previous = new Point(); boolean WaitForRealNumber = false; for(xpix = -1, x = settings.getXmin(); xpix < (int) size.getWidth(); xpix++, x+=step) { y = f.Calc(x); if(Double.isNaN(y)) { double tmpX = Calculate.FindLastXBeforeNaN(f, x - step); if(!Double.isNaN(tmpX)) { double tmpY = f.Calc(tmpX); ypix = (int) ((settings.getYmax() - tmpY) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); g.drawLine(previous.x, previous.y, xpix, ypix); } previous = null; if(!WaitForRealNumber) { WaitForRealNumber = true; } continue; } else if(WaitForRealNumber) WaitForRealNumber = false; ypix = (int) ((settings.getYmax() - y) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); if(xpix > -1) { if(previous == null) { g.drawRect(xpix, ypix, 1, 1); } else if(Math.abs(xpix - previous.x) < size.getWidth() && Math.abs(ypix - previous.y) < size.getHeight()) { g.drawLine(previous.x, previous.y, xpix, ypix); } if(fill && x >= FillLowX && x <= FillUpX) { g.setColor(Util.lighter(f.getColor())); ((Graphics2D) g).setStroke(new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL)); if(y > 0) { g.drawLine(xpix, ypix-1, xpix, this.XaxisY); } else if(y < 0) { g.drawLine(xpix, ypix+1, xpix, this.XaxisY); } ((Graphics2D) g).setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); g.setColor(f.getColor()); } } if(previous == null) previous = new Point(); previous.setLocation(xpix, ypix); } g.setColor(Color.BLACK); }
private void drawFunction(Function f, boolean fill, Graphics g) { if(f.isEmpty()) return; g.setColor(f.getColor()); int xpix, ypix; double x,y; double step = ((double) (settings.getXmax() - settings.getXmin())) / size.getWidth(); Point previous = new Point(); boolean WaitForRealNumber = false; for(xpix = -1, x = settings.getXmin(); xpix < (int) size.getWidth(); xpix++, x+=step) { y = f.Calc(x); if(Double.isNaN(y)) { double tmpX = Calculate.FindLastXBeforeNaN(f, x - step); if(!Double.isNaN(tmpX)) { double tmpY = f.Calc(tmpX); ypix = (int) ((settings.getYmax() - tmpY) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); g.drawLine(previous.x, previous.y, xpix, ypix); } previous = null; if(!WaitForRealNumber) { WaitForRealNumber = true; } continue; } else if(WaitForRealNumber) WaitForRealNumber = false; ypix = (int) ((settings.getYmax() - y) * (size.getHeight() / (settings.getYmax() - settings.getYmin()))); if(xpix > -1) { if(previous == null) { g.drawRect(xpix, ypix, 1, 1); } else if(Math.abs(xpix - previous.x) < size.getWidth() && Math.abs(ypix - previous.y) < size.getHeight()) { g.drawLine(previous.x, previous.y, xpix, ypix); } if(fill && x >= FillLowX && x <= FillUpX) { g.setColor(Util.lighter(f.getColor())); ((Graphics2D) g).setStroke(new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL)); if(y > 0) { if(ypix < 0) g.drawLine(xpix, 0, xpix, this.XaxisY); else g.drawLine(xpix, ypix-1, xpix, this.XaxisY); } else if(y < 0) { if(ypix > size.getHeight()) g.drawLine(xpix, (int) size.getHeight(), xpix, this.XaxisY); else g.drawLine(xpix, ypix+1, xpix, this.XaxisY); } ((Graphics2D) g).setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); g.setColor(f.getColor()); } } if(previous == null) previous = new Point(); previous.setLocation(xpix, ypix); } g.setColor(Color.BLACK); }
diff --git a/openFaces/source/org/openfaces/util/ResourceFilter.java b/openFaces/source/org/openfaces/util/ResourceFilter.java index 975b384b1..98e3c5a1e 100644 --- a/openFaces/source/org/openfaces/util/ResourceFilter.java +++ b/openFaces/source/org/openfaces/util/ResourceFilter.java @@ -1,528 +1,528 @@ /* * OpenFaces - JSF Component Library 2.0 * Copyright (C) 2007-2009, TeamDev Ltd. * [email protected] * Unless agreed in writing the contents of this file are subject to * the GNU Lesser General Public License Version 2.1 (the "LGPL" License). * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * Please visit http://openfaces.org/licensing/ for more details. */ package org.openfaces.util; import org.openfaces.ajax.AjaxViewHandler; import org.openfaces.renderkit.output.DynamicImageRenderer; import javax.faces.application.ViewExpiredException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Kharchenko */ public class ResourceFilter implements Filter { public static final String INTERNAL_RESOURCE_PATH = "/openFacesResources/"; public static final String RUNTIME_INIT_LIBRARY_PATH = INTERNAL_RESOURCE_PATH + "of_ajaxInitLib/"; private static final String PROCESSING_FILTER = "OF:ResourceFilter.doFilter_executing"; private static final long DEFAULT_LAST_MODIFIED_TIME = System.currentTimeMillis(); private static final String RESOURCE_CACHE = ResourceFilter.class.getName() + ".resourcesCache"; private static final String RESET_CSS_CONTEXT_PARAM = "org.openfaces.resetCSS"; private static final String RESET_CSS_CONTEXT_PARAM_DEFAULT_VALUE = "default"; private ServletContext servletContext; public void init(FilterConfig filterConfig) throws ServletException { servletContext = filterConfig.getServletContext(); } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest.getAttribute(PROCESSING_FILTER) != null) { filterChain.doFilter(servletRequest, servletResponse); return; } servletRequest.setAttribute(PROCESSING_FILTER, "true"); HttpServletResponse response = (HttpServletResponse) servletResponse; boolean internalResourceRequested = isInternalResourceRequested((HttpServletRequest) servletRequest); // todo: runtime-library-init-script is a special case of internal resource (according to url) - refactor this boolean runtimeLibraryInitScriptsRequested = isRuntimeInitScriptsRequested((HttpServletRequest) servletRequest); if (runtimeLibraryInitScriptsRequested) { processRuntimeInitLibrary((HttpServletRequest) servletRequest, response); } else if (internalResourceRequested) { processInternalResource((HttpServletRequest) servletRequest, response, filterChain, servletContext); } else if (isJavaScriptLibraryRequested((HttpServletRequest) servletRequest)) { // int sizeBefore = response.getOutputSize(); filterChain.doFilter(servletRequest, response); // int sizeAfter = response.getOutputSize(); // boolean jsWasServed = true;//sizeAfter - sizeBefore > 0; // if (jsWasServed) { // this (jsWasServed) check is needed for a case when the filter returns the 304 "Not Modified" Http result // without writing the output to the stream (was reproduced on WebLogic Portal for its own js-files). // we can't detect the http result so we check if anything was written to the outputStream String libName = getDecodedResourcePath((HttpServletRequest) servletRequest); ServletOutputStream outputStream = response.getOutputStream(); appendJavaScriptLoadingScript(libName, outputStream); // } } else { ResponseWrapper responseWrapper = new ResponseWrapper(response); try { filterChain.doFilter(servletRequest, responseWrapper); } catch (ServletException e) { if (e.getRootCause() instanceof Exception) { Exception exception = (Exception) e.getRootCause(); while (exception instanceof ServletException) { exception = (Exception) ((ServletException) exception).getRootCause(); } - if (exception instanceof ViewExpiredException) { + if (exception instanceof ViewExpiredException && AjaxUtil.isAjaxRequest(RequestFacade.getInstance(servletRequest))) { String requestURI = getDecodedResourcePath((HttpServletRequest) servletRequest); String ajaxParameters; StringBuilder stringBuffer = new StringBuilder(); Enumeration parameters = servletRequest.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); if (parameterName.equalsIgnoreCase(AjaxUtil.PARAM_RENDER) || parameterName.equalsIgnoreCase(AjaxUtil.AJAX_REQUEST_MARKER)) stringBuffer.append(parameterName).append("="). append(servletRequest.getParameter(parameterName)).append("&"); } ajaxParameters = stringBuffer.toString(); if (ajaxParameters != null && ajaxParameters.length() > 0) { String redirectURL = requestURI + "?" + ajaxParameters + "of_sessionExpiration=true"; String url = response.encodeRedirectURL(redirectURL); response.sendRedirect(url); } } else { throw new ServletException(e); // todo: shouldn't it be just "throw e" ? needs to be tested. } } } // todo (optimize): seems that servletResponse.getContentType() can be used to skip trying to process header includes for text/html pages String responseString = responseWrapper.getOutputAsString(); String errorOccured = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_OCCURED); if (errorOccured != null) { String errorMessage = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_MESSAGE_HEADER); response.setHeader(AjaxViewHandler.ERROR_MESSAGE_HEADER, errorMessage); servletResponse.setContentType("text/xml;charset=UTF-8"); return; } String sessionExpiredResponse = (String) servletRequest.getAttribute(AjaxViewHandler.SESSION_EXPIRED_RESPONSE); if (sessionExpiredResponse != null) { responseString = sessionExpiredResponse; } if (responseString.length() == 0) return; if (ResourceUtil.isHeaderIncludesRegistered(servletRequest)) { renderResponseWithHeader(servletRequest, servletResponse, responseString); return; } if (sessionExpiredResponse != null) { servletResponse.setContentType("text/xml;charset=UTF-8"); String location = (String) servletRequest.getAttribute(AjaxViewHandler.LOCATION_HEADER); if (servletResponse instanceof HttpServletResponse) { response.setHeader(AjaxViewHandler.LOCATION_HEADER, location); } servletResponse.getOutputStream().write(responseString.getBytes()); return; } servletResponse.getOutputStream().write(responseWrapper.getOutputAsByteArray()); } } public void destroy() { } private void appendJavaScriptLoadingScript(String jsLibName, OutputStream os) throws IOException { String result = "\n\n//AUTO GENERATED CODE\n\nwindow['_of_loadedLibrary:" + jsLibName + "'] = true;"; os.write(result.getBytes("UTF-8")); } private void processInternalResource(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, ServletContext servletContext) throws IOException, ServletException { String uri = getDecodedResourcePath(request); int packageStartIndex = uri.indexOf(INTERNAL_RESOURCE_PATH) + INTERNAL_RESOURCE_PATH.length() - 1; String resourcePathWithVersion = uri.substring(packageStartIndex); String resourcePath; boolean isDynamicImageResource = RenderingUtil.isDynamicResource(uri); if (!isDynamicImageResource) { int versionPrefixIdx = resourcePathWithVersion.lastIndexOf("-"); if (versionPrefixIdx != -1) resourcePath = resourcePathWithVersion.substring(0, versionPrefixIdx) + resourcePathWithVersion.substring(resourcePathWithVersion.lastIndexOf(".")); else { // some rare internal resources are allowed to come without version, // e.g. for images referred to from default.css (see clear.gif as an example) resourcePath = resourcePathWithVersion; } } else { resourcePath = resourcePathWithVersion; } InputStream inputStream; if (isDynamicImageResource) { inputStream = getDynamicImageAsInputStream(request, servletContext); response.setContentType(getImageContentType(uri)); } else { if (!resourcePath.startsWith("/org/openfaces")) { // SECURITY ISSUE: DO NOT LET TO ACCESS /openFacesResources/ HOME AS IT PROVIDES SERVER'S FILES response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } URL resourceURL = RenderingUtil.class.getResource(resourcePath); if (resourceURL == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } File resourceFile = getResourceFile(resourceURL); long lastModified = resourceFile != null ? resourceFile.lastModified() : -1; if (request.getDateHeader("If-Modified-Since") != -1) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } if (lastModified != -1) { lastModified -= lastModified % 1000; long requestModifiedSince = request.getDateHeader("If-Modified-Since"); if (lastModified <= requestModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } byte[] resource = getCachedResource(servletContext, resourcePath); if (resource == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } inputStream = new ByteArrayInputStream(resource); if (resourcePath.endsWith(".js")) { response.setContentType("text/javascript"); // this can be added after GZip of all javascript files // response.setContentType("application/x-javascript"); // response.addHeader("Content-Encoding", "gzip"); } else if (resourcePath.endsWith(".css")) response.setContentType("text/css"); else if (resourcePath.endsWith(".gif")) response.setContentType("image/gif"); else if (resourcePath.endsWith(".png")) response.setContentType("image/png"); else if (resourcePath.endsWith(".jpg") || resourcePath.endsWith(".jpeg")) response.setContentType("image/jpeg"); else if (resourcePath.endsWith(".xml") || resourcePath.endsWith(".xsl")) response.setContentType("text/xml"); response.setDateHeader("Last-Modified", lastModified != -1 ? lastModified : DEFAULT_LAST_MODIFIED_TIME); response.setHeader("Cache-Control", "must-revalidate"); // response.setHeader("ETag", String.valueOf(lastModified != -1 ? lastModified : DEFAULT_LAST_MODIFIED_TIME)); } if (inputStream != null) { OutputStream outputStream = response.getOutputStream(); int result; while ((result = inputStream.read()) != -1) { outputStream.write(result); } if (uri.endsWith(".js")) appendJavaScriptLoadingScript(getDecodedResourcePath(request), outputStream); outputStream.close(); } else { filterChain.doFilter(request, response); } } /** * Returns path of the requested resource within servlet context after any container decoding, such as removing * jsessionid suffixes. */ private String getDecodedResourcePath(HttpServletRequest request) { String uri = request.getPathInfo(); if (uri == null) uri = request.getRequestURI(); return uri; } private byte[] getStreamAsByteArray(InputStream stream) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); BufferedInputStream bStream = new BufferedInputStream(stream); byte[] array = new byte[1024]; int readed = 0; while (readed != -1) { readed = bStream.read(array); if (readed != -1) { byteStream.write(array, 0, readed); } } return byteStream.toByteArray(); } private byte[] getCachedResource(ServletContext servletContext, String resourcePath) throws IOException { Map cache = getCache(servletContext); byte[] resource = (cache.get(resourcePath) != null) ? ((byte[]) cache.get(resourcePath)) : null; if (resource == null) { InputStream inputStream = RenderingUtil.class.getResourceAsStream(resourcePath); try { resource = getStreamAsByteArray(inputStream); cache.put(resourcePath, resource); } finally { inputStream.close(); } } return resource; } private Map getCache(ServletContext servletContext) { Map cache = (Map) servletContext.getAttribute(RESOURCE_CACHE); if (cache == null) { cache = new HashMap(); servletContext.setAttribute(RESOURCE_CACHE, cache); } return cache; } private File getResourceFile(URL resourceUrl) { String protocol = resourceUrl.getProtocol(); if (protocol.equals("file")) return new File(resourceUrl.getPath()); if (!protocol.equals("jar")) return null; String path = resourceUrl.getPath(); if (!path.startsWith("file")) return null; path = path.substring("file".length() + 1); path = path.substring(0, path.indexOf("!")); return new File(path); } private String getImageContentType(String uri) { if (uri.toLowerCase().indexOf(".gif") > -1) return "image/gif"; if (uri.toLowerCase().indexOf(".png") > -1) return "image/png"; if ((uri.toLowerCase().indexOf(".jpg") > -1) || uri.toLowerCase().indexOf(".jpeg") > -1) return "image/jpeg"; return "image"; } private InputStream getDynamicImageAsInputStream(HttpServletRequest request, ServletContext servletContext) { String sid = request.getParameter("id"); if (sid == null) { servletContext.log("Couldn't retrieve dynamic image id from request: " + getDecodedResourcePath(request)); return null; } HttpSession session = request.getSession(); DynamicImagePool pool = (DynamicImagePool) session.getAttribute(DynamicImageRenderer.IMAGE_POOL); if (pool == null) { servletContext.log("Couldn't retrieve image pool on processing a dynamic image request"); return null; } byte[] image = pool.getImage(sid); if (image == null) { servletContext.log("Image was not found in pool: " + sid); return null; } return new ByteArrayInputStream(image); } private void renderResponseWithHeader( ServletRequest servletRequest, ServletResponse servletResponse, String responseString) throws IOException { int headerInsertionPos; boolean hasHeaderTag = false; StringInspector responseStringInspector = new StringInspector(responseString); if ((headerInsertionPos = responseStringInspector.indexOfIgnoreCase("<head")) >= 0) { int headerOpeningTagEnd = responseString.indexOf('>', headerInsertionPos); if (headerOpeningTagEnd != -1) { headerInsertionPos = headerOpeningTagEnd + 1; hasHeaderTag = true; } else headerInsertionPos = 0; } else { headerInsertionPos = responseStringInspector.indexOfIgnoreCase("<body"); if (headerInsertionPos == -1) { int htmlStart = responseStringInspector.indexOfIgnoreCase("<html"); if (htmlStart != -1) headerInsertionPos = responseString.indexOf('>', htmlStart) + 1; else headerInsertionPos = 0; } } PrintWriter writer = servletResponse.getWriter(); if (headerInsertionPos > 0) { writer.write(responseString.substring(0, headerInsertionPos)); } if (!hasHeaderTag) { writer.write("<head>"); } List<String> jsLibraries = (List<String>) servletRequest.getAttribute(ResourceUtil.HEADER_JS_LIBRARIES); if (jsLibraries != null) { for (String jsFileUrl : jsLibraries) { writer.print("<script type=\"text/javascript\" src=\""); writer.print(jsFileUrl); writer.println("\"></script>"); } } HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String resetCss = httpServletRequest.getSession().getServletContext().getInitParameter(RESET_CSS_CONTEXT_PARAM); if (resetCss != null) { resetCss = resetCss.trim(); String resetCssUrl; if (resetCss.equals(RESET_CSS_CONTEXT_PARAM_DEFAULT_VALUE)) { resetCssUrl = httpServletRequest.getContextPath() + INTERNAL_RESOURCE_PATH + "org/openfaces/renderkit/reset" + "-" + ResourceUtil.getVersionString() + ".css"; } else if (!resetCss.startsWith("/") && !resetCss.startsWith("http://")) { resetCssUrl = httpServletRequest.getContextPath() + "/" + resetCss; } else { resetCssUrl = resetCss; } writer.print("<link type=\"text/css\" href=\""); writer.print(resetCssUrl); writer.println("\" rel=\"stylesheet\"/>"); } writer.print("<link type=\"text/css\" href=\""); String defaultCssUrl = httpServletRequest.getContextPath() + INTERNAL_RESOURCE_PATH + "org/openfaces/renderkit/default" + "-" + ResourceUtil.getVersionString() + ".css"; writer.print(defaultCssUrl); writer.println("\" rel=\"stylesheet\"/>"); if (!hasHeaderTag) { writer.write("</head>"); } StringInspector restOfResponse; if (headerInsertionPos == -1) restOfResponse = responseStringInspector; else restOfResponse = responseStringInspector.substring(headerInsertionPos); StringBuilder onLoadScripts = (StringBuilder) servletRequest.getAttribute(RenderingUtil.ON_LOAD_SCRIPTS_KEY); if (onLoadScripts == null) onLoadScripts = new StringBuilder(); else { if (onLoadScripts.length() > 0) onLoadScripts.insert(0, "<script type=\"text/javascript\">\n").append("\n</script>\n"); } if (onLoadScripts.length() == 0) { writer.write(restOfResponse.toString()); return; } int bodyCloseTagPos = restOfResponse.indexOfIgnoreCase("</body>"); if (bodyCloseTagPos == -1) { writer.write(restOfResponse.toString()); writer.write(onLoadScripts.toString()); } else { String bodyContents = restOfResponse.toString().substring(0, bodyCloseTagPos); writer.write(bodyContents); writer.write(onLoadScripts.toString()); String bodyCloseTag = restOfResponse.toString().substring(bodyCloseTagPos); writer.write(bodyCloseTag); } } private void processRuntimeInitLibrary(HttpServletRequest request, HttpServletResponse response) throws IOException { String requestUri = getDecodedResourcePath(request); HttpSession session = request.getSession(); int prefixIdx = requestUri.indexOf(RUNTIME_INIT_LIBRARY_PATH); String sessionMapKey = requestUri.substring(prefixIdx); String initializationScripts = (String) session.getAttribute(sessionMapKey); if (initializationScripts == null) { Enumeration sessionAttributes = session.getAttributeNames(); while (sessionAttributes.hasMoreElements()) { String sessionAttribute = (String) sessionAttributes.nextElement(); if (sessionAttribute.indexOf(sessionMapKey) != -1) { initializationScripts = (String) session.getAttribute(sessionAttribute); session.removeAttribute(sessionAttribute); break; } } } session.removeAttribute(requestUri); if (initializationScripts != null && initializationScripts.length() > 0) { OutputStream outputStream = response.getOutputStream(); outputStream.write(initializationScripts.getBytes()); outputStream.close(); } else { //todo: what to do? } } private boolean isRuntimeInitScriptsRequested(HttpServletRequest request) { return getDecodedResourcePath(request).indexOf(RUNTIME_INIT_LIBRARY_PATH) != -1; } private boolean isJavaScriptLibraryRequested(HttpServletRequest request) { String requestURI = getDecodedResourcePath(request); return requestURI.toLowerCase().endsWith(".js"); } /** * Checks whether request is for internal resource or not. * * @param request incoming request. * @return <code>true</code> - if request is for internal resource. <code>false</code> otherwise. */ private boolean isInternalResourceRequested(HttpServletRequest request) { return getDecodedResourcePath(request).indexOf(INTERNAL_RESOURCE_PATH) != -1; } }
true
true
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest.getAttribute(PROCESSING_FILTER) != null) { filterChain.doFilter(servletRequest, servletResponse); return; } servletRequest.setAttribute(PROCESSING_FILTER, "true"); HttpServletResponse response = (HttpServletResponse) servletResponse; boolean internalResourceRequested = isInternalResourceRequested((HttpServletRequest) servletRequest); // todo: runtime-library-init-script is a special case of internal resource (according to url) - refactor this boolean runtimeLibraryInitScriptsRequested = isRuntimeInitScriptsRequested((HttpServletRequest) servletRequest); if (runtimeLibraryInitScriptsRequested) { processRuntimeInitLibrary((HttpServletRequest) servletRequest, response); } else if (internalResourceRequested) { processInternalResource((HttpServletRequest) servletRequest, response, filterChain, servletContext); } else if (isJavaScriptLibraryRequested((HttpServletRequest) servletRequest)) { // int sizeBefore = response.getOutputSize(); filterChain.doFilter(servletRequest, response); // int sizeAfter = response.getOutputSize(); // boolean jsWasServed = true;//sizeAfter - sizeBefore > 0; // if (jsWasServed) { // this (jsWasServed) check is needed for a case when the filter returns the 304 "Not Modified" Http result // without writing the output to the stream (was reproduced on WebLogic Portal for its own js-files). // we can't detect the http result so we check if anything was written to the outputStream String libName = getDecodedResourcePath((HttpServletRequest) servletRequest); ServletOutputStream outputStream = response.getOutputStream(); appendJavaScriptLoadingScript(libName, outputStream); // } } else { ResponseWrapper responseWrapper = new ResponseWrapper(response); try { filterChain.doFilter(servletRequest, responseWrapper); } catch (ServletException e) { if (e.getRootCause() instanceof Exception) { Exception exception = (Exception) e.getRootCause(); while (exception instanceof ServletException) { exception = (Exception) ((ServletException) exception).getRootCause(); } if (exception instanceof ViewExpiredException) { String requestURI = getDecodedResourcePath((HttpServletRequest) servletRequest); String ajaxParameters; StringBuilder stringBuffer = new StringBuilder(); Enumeration parameters = servletRequest.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); if (parameterName.equalsIgnoreCase(AjaxUtil.PARAM_RENDER) || parameterName.equalsIgnoreCase(AjaxUtil.AJAX_REQUEST_MARKER)) stringBuffer.append(parameterName).append("="). append(servletRequest.getParameter(parameterName)).append("&"); } ajaxParameters = stringBuffer.toString(); if (ajaxParameters != null && ajaxParameters.length() > 0) { String redirectURL = requestURI + "?" + ajaxParameters + "of_sessionExpiration=true"; String url = response.encodeRedirectURL(redirectURL); response.sendRedirect(url); } } else { throw new ServletException(e); // todo: shouldn't it be just "throw e" ? needs to be tested. } } } // todo (optimize): seems that servletResponse.getContentType() can be used to skip trying to process header includes for text/html pages String responseString = responseWrapper.getOutputAsString(); String errorOccured = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_OCCURED); if (errorOccured != null) { String errorMessage = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_MESSAGE_HEADER); response.setHeader(AjaxViewHandler.ERROR_MESSAGE_HEADER, errorMessage); servletResponse.setContentType("text/xml;charset=UTF-8"); return; } String sessionExpiredResponse = (String) servletRequest.getAttribute(AjaxViewHandler.SESSION_EXPIRED_RESPONSE); if (sessionExpiredResponse != null) { responseString = sessionExpiredResponse; } if (responseString.length() == 0) return; if (ResourceUtil.isHeaderIncludesRegistered(servletRequest)) { renderResponseWithHeader(servletRequest, servletResponse, responseString); return; } if (sessionExpiredResponse != null) { servletResponse.setContentType("text/xml;charset=UTF-8"); String location = (String) servletRequest.getAttribute(AjaxViewHandler.LOCATION_HEADER); if (servletResponse instanceof HttpServletResponse) { response.setHeader(AjaxViewHandler.LOCATION_HEADER, location); } servletResponse.getOutputStream().write(responseString.getBytes()); return; } servletResponse.getOutputStream().write(responseWrapper.getOutputAsByteArray()); } }
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest.getAttribute(PROCESSING_FILTER) != null) { filterChain.doFilter(servletRequest, servletResponse); return; } servletRequest.setAttribute(PROCESSING_FILTER, "true"); HttpServletResponse response = (HttpServletResponse) servletResponse; boolean internalResourceRequested = isInternalResourceRequested((HttpServletRequest) servletRequest); // todo: runtime-library-init-script is a special case of internal resource (according to url) - refactor this boolean runtimeLibraryInitScriptsRequested = isRuntimeInitScriptsRequested((HttpServletRequest) servletRequest); if (runtimeLibraryInitScriptsRequested) { processRuntimeInitLibrary((HttpServletRequest) servletRequest, response); } else if (internalResourceRequested) { processInternalResource((HttpServletRequest) servletRequest, response, filterChain, servletContext); } else if (isJavaScriptLibraryRequested((HttpServletRequest) servletRequest)) { // int sizeBefore = response.getOutputSize(); filterChain.doFilter(servletRequest, response); // int sizeAfter = response.getOutputSize(); // boolean jsWasServed = true;//sizeAfter - sizeBefore > 0; // if (jsWasServed) { // this (jsWasServed) check is needed for a case when the filter returns the 304 "Not Modified" Http result // without writing the output to the stream (was reproduced on WebLogic Portal for its own js-files). // we can't detect the http result so we check if anything was written to the outputStream String libName = getDecodedResourcePath((HttpServletRequest) servletRequest); ServletOutputStream outputStream = response.getOutputStream(); appendJavaScriptLoadingScript(libName, outputStream); // } } else { ResponseWrapper responseWrapper = new ResponseWrapper(response); try { filterChain.doFilter(servletRequest, responseWrapper); } catch (ServletException e) { if (e.getRootCause() instanceof Exception) { Exception exception = (Exception) e.getRootCause(); while (exception instanceof ServletException) { exception = (Exception) ((ServletException) exception).getRootCause(); } if (exception instanceof ViewExpiredException && AjaxUtil.isAjaxRequest(RequestFacade.getInstance(servletRequest))) { String requestURI = getDecodedResourcePath((HttpServletRequest) servletRequest); String ajaxParameters; StringBuilder stringBuffer = new StringBuilder(); Enumeration parameters = servletRequest.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); if (parameterName.equalsIgnoreCase(AjaxUtil.PARAM_RENDER) || parameterName.equalsIgnoreCase(AjaxUtil.AJAX_REQUEST_MARKER)) stringBuffer.append(parameterName).append("="). append(servletRequest.getParameter(parameterName)).append("&"); } ajaxParameters = stringBuffer.toString(); if (ajaxParameters != null && ajaxParameters.length() > 0) { String redirectURL = requestURI + "?" + ajaxParameters + "of_sessionExpiration=true"; String url = response.encodeRedirectURL(redirectURL); response.sendRedirect(url); } } else { throw new ServletException(e); // todo: shouldn't it be just "throw e" ? needs to be tested. } } } // todo (optimize): seems that servletResponse.getContentType() can be used to skip trying to process header includes for text/html pages String responseString = responseWrapper.getOutputAsString(); String errorOccured = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_OCCURED); if (errorOccured != null) { String errorMessage = (String) servletRequest.getAttribute(AjaxViewHandler.ERROR_MESSAGE_HEADER); response.setHeader(AjaxViewHandler.ERROR_MESSAGE_HEADER, errorMessage); servletResponse.setContentType("text/xml;charset=UTF-8"); return; } String sessionExpiredResponse = (String) servletRequest.getAttribute(AjaxViewHandler.SESSION_EXPIRED_RESPONSE); if (sessionExpiredResponse != null) { responseString = sessionExpiredResponse; } if (responseString.length() == 0) return; if (ResourceUtil.isHeaderIncludesRegistered(servletRequest)) { renderResponseWithHeader(servletRequest, servletResponse, responseString); return; } if (sessionExpiredResponse != null) { servletResponse.setContentType("text/xml;charset=UTF-8"); String location = (String) servletRequest.getAttribute(AjaxViewHandler.LOCATION_HEADER); if (servletResponse instanceof HttpServletResponse) { response.setHeader(AjaxViewHandler.LOCATION_HEADER, location); } servletResponse.getOutputStream().write(responseString.getBytes()); return; } servletResponse.getOutputStream().write(responseWrapper.getOutputAsByteArray()); } }
diff --git a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java index 88e02cf..96e829e 100644 --- a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java +++ b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java @@ -1,75 +1,76 @@ package dk.statsbiblioteket.broadcasttranscoder; import dk.statsbiblioteket.broadcasttranscoder.cli.SingleTranscodingContext; import dk.statsbiblioteket.broadcasttranscoder.cli.parsers.SingleTranscodingOptionsParser; import dk.statsbiblioteket.broadcasttranscoder.persistence.entities.ReklamefilmTranscodingRecord; import dk.statsbiblioteket.broadcasttranscoder.processors.*; import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.FfprobeFetcherProcessor; import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.GoNoGoProcessor; import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmFileResolverProcessor; import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmPersistentRecordEnricherProcessor; import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmFileResolverImpl; import dk.statsbiblioteket.broadcasttranscoder.util.FileUtils; import dk.statsbiblioteket.broadcasttranscoder.persistence.dao.HibernateUtil; import dk.statsbiblioteket.broadcasttranscoder.persistence.dao.ReklamefilmTranscodingRecordDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; /** * */ public class ReklamefilmTranscoderApplication extends TranscoderApplication { private static Logger logger = LoggerFactory.getLogger(ReklamefilmTranscoderApplication.class); public static void main(String[] args) throws Exception { logger.debug("Entered main method."); SingleTranscodingContext<ReklamefilmTranscodingRecord> context = new SingleTranscodingOptionsParser<ReklamefilmTranscodingRecord>().parseOptions(args); HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath()); context.setTranscodingProcessInterface(new ReklamefilmTranscodingRecordDAO(util)); context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context)); TranscodeRequest request = new TranscodeRequest(); + request.setObjectPid(context.getProgrampid()); try { request.setGoForTranscoding(true); ProcessorChainElement gonogoer = new GoNoGoProcessor(); ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer); firstChain.processIteratively(request, context); if (request.isGoForTranscoding()) { ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor(); ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor(); ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor(); ProcessorChainElement renamer = new FinalMediaFileRenamerProcessor(); ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor(); ProcessorChainElement ffprober = new FfprobeFetcherProcessor(); ProcessorChainElement snapshotter = new SnapshotExtractorProcessor(); ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor(); ProcessorChainElement secondChain = ProcessorChainElement.makeChain( resolver, aspecter, transcoder, renamer, zeroChecker, ffprober, snapshotter, reklamePersistenceEnricher ); secondChain.processIteratively(request, context); } } catch (Exception e) { transcodingFailed(request,context,e); //Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it //failed on. logger.error("Error processing " + request.getObjectPid(), e); throw(e); } transcodingComplete(request,context); } }
true
true
public static void main(String[] args) throws Exception { logger.debug("Entered main method."); SingleTranscodingContext<ReklamefilmTranscodingRecord> context = new SingleTranscodingOptionsParser<ReklamefilmTranscodingRecord>().parseOptions(args); HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath()); context.setTranscodingProcessInterface(new ReklamefilmTranscodingRecordDAO(util)); context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context)); TranscodeRequest request = new TranscodeRequest(); try { request.setGoForTranscoding(true); ProcessorChainElement gonogoer = new GoNoGoProcessor(); ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer); firstChain.processIteratively(request, context); if (request.isGoForTranscoding()) { ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor(); ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor(); ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor(); ProcessorChainElement renamer = new FinalMediaFileRenamerProcessor(); ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor(); ProcessorChainElement ffprober = new FfprobeFetcherProcessor(); ProcessorChainElement snapshotter = new SnapshotExtractorProcessor(); ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor(); ProcessorChainElement secondChain = ProcessorChainElement.makeChain( resolver, aspecter, transcoder, renamer, zeroChecker, ffprober, snapshotter, reklamePersistenceEnricher ); secondChain.processIteratively(request, context); } } catch (Exception e) { transcodingFailed(request,context,e); //Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it //failed on. logger.error("Error processing " + request.getObjectPid(), e); throw(e); } transcodingComplete(request,context); }
public static void main(String[] args) throws Exception { logger.debug("Entered main method."); SingleTranscodingContext<ReklamefilmTranscodingRecord> context = new SingleTranscodingOptionsParser<ReklamefilmTranscodingRecord>().parseOptions(args); HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath()); context.setTranscodingProcessInterface(new ReklamefilmTranscodingRecordDAO(util)); context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context)); TranscodeRequest request = new TranscodeRequest(); request.setObjectPid(context.getProgrampid()); try { request.setGoForTranscoding(true); ProcessorChainElement gonogoer = new GoNoGoProcessor(); ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer); firstChain.processIteratively(request, context); if (request.isGoForTranscoding()) { ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor(); ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor(); ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor(); ProcessorChainElement renamer = new FinalMediaFileRenamerProcessor(); ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor(); ProcessorChainElement ffprober = new FfprobeFetcherProcessor(); ProcessorChainElement snapshotter = new SnapshotExtractorProcessor(); ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor(); ProcessorChainElement secondChain = ProcessorChainElement.makeChain( resolver, aspecter, transcoder, renamer, zeroChecker, ffprober, snapshotter, reklamePersistenceEnricher ); secondChain.processIteratively(request, context); } } catch (Exception e) { transcodingFailed(request,context,e); //Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it //failed on. logger.error("Error processing " + request.getObjectPid(), e); throw(e); } transcodingComplete(request,context); }
diff --git a/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java b/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java index 9a05b7a..c9c425d 100644 --- a/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java +++ b/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java @@ -1,90 +1,90 @@ package com.metaweb.gridworks.operations; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import com.metaweb.gridworks.browsing.Engine; import com.metaweb.gridworks.browsing.FilteredRows; import com.metaweb.gridworks.browsing.RowVisitor; import com.metaweb.gridworks.history.Change; import com.metaweb.gridworks.history.HistoryEntry; import com.metaweb.gridworks.model.AbstractOperation; import com.metaweb.gridworks.model.Project; import com.metaweb.gridworks.model.Row; import com.metaweb.gridworks.model.changes.MassChange; import com.metaweb.gridworks.model.changes.RowFlagChange; public class RowFlagOperation extends EngineDependentOperation { final protected boolean _flagged; static public AbstractOperation reconstruct(Project project, JSONObject obj) throws Exception { JSONObject engineConfig = obj.getJSONObject("engineConfig"); boolean flagged = obj.getBoolean("flagged"); return new RowFlagOperation( engineConfig, flagged ); } public RowFlagOperation(JSONObject engineConfig, boolean flagged) { super(engineConfig); _flagged = flagged; } public void write(JSONWriter writer, Properties options) throws JSONException { writer.object(); writer.key("op"); writer.value(OperationRegistry.s_opClassToName.get(this.getClass())); writer.key("description"); writer.value(getBriefDescription(null)); writer.key("engineConfig"); writer.value(getEngineConfig()); writer.key("flagged"); writer.value(_flagged); writer.endObject(); } protected String getBriefDescription(Project project) { return (_flagged ? "Flag rows" : "Unflag rows"); } protected HistoryEntry createHistoryEntry(Project project) throws Exception { Engine engine = createEngine(project); List<Change> changes = new ArrayList<Change>(project.rows.size()); FilteredRows filteredRows = engine.getAllFilteredRows(false); filteredRows.accept(project, createRowVisitor(project, changes)); return new HistoryEntry( project, (_flagged ? "Flag" : "Unflag") + " " + changes.size() + " rows", this, new MassChange(changes, false) ); } protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception { return new RowVisitor() { List<Change> changes; public RowVisitor init(List<Change> changes) { this.changes = changes; return this; } public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) { - if (row.starred != _flagged) { + if (row.flagged != _flagged) { RowFlagChange change = new RowFlagChange(rowIndex, _flagged); changes.add(change); } return false; } }.init(changes); } }
true
true
protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception { return new RowVisitor() { List<Change> changes; public RowVisitor init(List<Change> changes) { this.changes = changes; return this; } public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) { if (row.starred != _flagged) { RowFlagChange change = new RowFlagChange(rowIndex, _flagged); changes.add(change); } return false; } }.init(changes); }
protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception { return new RowVisitor() { List<Change> changes; public RowVisitor init(List<Change> changes) { this.changes = changes; return this; } public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) { if (row.flagged != _flagged) { RowFlagChange change = new RowFlagChange(rowIndex, _flagged); changes.add(change); } return false; } }.init(changes); }
diff --git a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/info/JavaStringELInfoHover.java b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/info/JavaStringELInfoHover.java index e5edd3dd..1d73ee9d 100644 --- a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/info/JavaStringELInfoHover.java +++ b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/info/JavaStringELInfoHover.java @@ -1,659 +1,659 @@ /******************************************************************************* * Copyright (c) 2010-2011 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jst.jsp.jspeditor.info; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Platform; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover; import org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLinks; import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IJavaPartitions; import org.eclipse.jface.internal.text.html.BrowserInformationControlInput; import org.eclipse.jface.internal.text.html.HTMLPrinter; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.rules.IToken; import org.eclipse.swt.graphics.FontData; import org.jboss.tools.common.el.core.model.ELInvocationExpression; import org.jboss.tools.common.el.core.model.ELModel; import org.jboss.tools.common.el.core.model.ELUtil; import org.jboss.tools.common.el.core.parser.ELParser; import org.jboss.tools.common.el.core.parser.ELParserUtil; import org.jboss.tools.common.el.core.resolver.ELContext; import org.jboss.tools.common.el.core.resolver.ELResolution; import org.jboss.tools.common.el.core.resolver.ELResolver; import org.jboss.tools.common.el.core.resolver.ELSegment; import org.jboss.tools.common.el.core.resolver.JavaMemberELSegmentImpl; import org.jboss.tools.common.el.ui.ca.ELProposalProcessor; import org.jboss.tools.common.model.XModelObject; import org.jboss.tools.common.text.TextProposal; import org.jboss.tools.common.util.StringUtil; import org.jboss.tools.jst.jsp.JspEditorPlugin; import org.jboss.tools.jst.jsp.contentassist.Utils; import org.jboss.tools.jst.web.kb.KbQuery; import org.jboss.tools.jst.web.kb.PageContextFactory; import org.jboss.tools.jst.web.kb.PageProcessor; import org.jboss.tools.jst.web.kb.KbQuery.Type; import org.jboss.tools.jst.web.kb.el.MessagePropertyELSegmentImpl; import org.osgi.framework.Bundle; /** * * @author Victor Rubezhny * */ @SuppressWarnings("restriction") public class JavaStringELInfoHover extends JavadocHover { // private IInformationControlCreator fPresenterControlCreator; /* * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } /* * @see JavaElementHover */ public String getHoverInfoDepracated(ITextViewer textViewer, IRegion region) { // find a region of __java_string, if we're in it - use it IDocument document = textViewer == null ? null : textViewer.getDocument(); if (document == null) return null; int rangeStart = -1; int rangeLength = 0; IToken rangeToken = null; FastJavaPartitionScanner scanner = new FastJavaPartitionScanner(); scanner.setRange(document, 0, document.getLength()); while(true) { IToken token = scanner.nextToken(); if(token == null || token.isEOF()) break; int start = scanner.getTokenOffset(); int length = scanner.getTokenLength(); int end = start + length; if(start <= region.getOffset() && end >= region.getOffset()) { rangeStart = start; rangeLength = length; rangeToken = token; break; } if(start > region.getOffset()) break; } if (rangeToken == null || rangeStart == -1 || rangeLength <=0 || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData())) return null; // OK. We've found JAVA_STRING token // Check that the position is in the EL if (!checkStartPosition(document, region.getOffset())) return null; // Calculate and prepare KB-query parameters String text = null; try { text = document.get(rangeStart, rangeLength); } catch (BadLocationException e) { JspEditorPlugin.getPluginLog().logError(e); } int inValueOffset = region.getOffset() - rangeStart; ELParser p = ELParserUtil.getJbossFactory().createParser(); ELModel model = p.parse(text); ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression if (ie == null) return null; String query = "#{" + ie.getText(); //$NON-NLS-1$ KbQuery kbQuery = Utils.createKbQuery(Type.ATTRIBUTE_VALUE, region.getOffset() + region.getLength(), query, query, "", "", null, null, false); //$NON-NLS-1$ //$NON-NLS-2$ ITypeRoot input= getEditorInputJavaElement(); if (input == null) return null; IFile file = null; try { IResource resource = input.getCorrespondingResource(); if (resource instanceof IFile) file = (IFile) resource; } catch (JavaModelException e) { // Ignore. It is probably because of Java element's resource is not found } if(file == null) { return null; } ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE); TextProposal[] proposals = PageProcessor.getInstance().getProposals(kbQuery, context); if (proposals == null) return null; for(TextProposal proposal : proposals) { String label = proposal == null ? null : proposal.getLabel(); label = (label == null || label.indexOf(':') == -1) ? label : label.substring(0, label.indexOf(':')).trim(); if (label != null && query.endsWith(label) && proposal != null && proposal.getContextInfo() != null && proposal.getContextInfo().trim().length() > 0) { return proposal.getContextInfo(); } } return null; } /* * @see org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) * @since 3.4 */ public Object getHoverInfo2(ITextViewer textViewer, IRegion region) { // find a region of __java_string, if we're in it - use it IDocument document = textViewer == null ? null : textViewer.getDocument(); if (document == null) return null; int rangeStart = -1; int rangeLength = 0; IToken rangeToken = null; FastJavaPartitionScanner scanner = new FastJavaPartitionScanner(); scanner.setRange(document, 0, document.getLength()); while(true) { IToken token = scanner.nextToken(); if(token == null || token.isEOF()) break; int start = scanner.getTokenOffset(); int length = scanner.getTokenLength(); int end = start + length; if(start <= region.getOffset() && end >= region.getOffset()) { rangeStart = start; rangeLength = length; rangeToken = token; break; } if(start > region.getOffset()) break; } if (rangeToken == null || rangeStart == -1 || rangeLength <=0 || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData())) return null; // OK. We've found JAVA_STRING token // Check that the position is in the EL if (!checkStartPosition(document, region.getOffset())) return null; // Calculate and prepare KB-query parameters String text = null; try { text = document.get(rangeStart, rangeLength); } catch (BadLocationException e) { JspEditorPlugin.getPluginLog().logError(e); } int inValueOffset = region.getOffset() - rangeStart; ELParser p = ELParserUtil.getJbossFactory().createParser(); ELModel model = p.parse(text); ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression if (ie == null) return null; ITypeRoot input= getEditorInputJavaElement(); if (input == null) return null; IResource r = input.getResource(); if(!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) { //$NON-NLS-1$ return null; } IFile file = (IFile)r; ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE); ELResolver[] resolvers = context.getElResolvers(); for (int i = 0; resolvers != null && i < resolvers.length; i++) { ELResolution resolution = resolvers[i] == null ? null : resolvers[i].resolve(context, ie, region.getOffset() + region.getLength()); if (resolution == null) continue; ELSegment segment = resolution.getLastSegment(); - if (!segment.isResolved()) continue; + if (segment==null || !segment.isResolved()) continue; if(segment instanceof JavaMemberELSegmentImpl) { JavaMemberELSegmentImpl jmSegment = (JavaMemberELSegmentImpl)segment; IJavaElement[] javaElements = jmSegment.getAllJavaElements(); if (javaElements == null || javaElements.length == 0) { if (jmSegment.getJavaElement() == null) continue; javaElements = new IJavaElement[] {jmSegment.getJavaElement()}; } if (javaElements == null || javaElements.length == 0) continue; return JavaStringELInfoHover.getHoverInfo2Internal(javaElements, true); } else if (segment instanceof MessagePropertyELSegmentImpl) { MessagePropertyELSegmentImpl mpSegment = (MessagePropertyELSegmentImpl)segment; String baseName = mpSegment.getBaseName(); String propertyName = mpSegment.isBundle() ? null : StringUtil.trimQuotes(segment.getToken().getText()); String hoverText = ELProposalProcessor.getELMessagesHoverInternal(baseName, propertyName, (List<XModelObject>)mpSegment.getObjects()); StringBuffer buffer = new StringBuffer(hoverText); HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet()); HTMLPrinter.addPageEpilog(buffer); return new ELInfoHoverBrowserInformationControlInput(null, new IJavaElement[0], buffer.toString(), 0); } } return null; } /* * Checks if the EL start starting characters are present * @param viewer * @param offset * @return * @throws BadLocationException */ private boolean checkStartPosition(IDocument document, int offset) { try { while (--offset >= 0) { if ('}' == document.getChar(offset)) return false; if ('"' == document.getChar(offset) && (offset - 1) >= 0 && '\\' != document.getChar(offset - 1)) { return false; } if ('{' == document.getChar(offset) && (offset - 1) >= 0 && ('#' == document.getChar(offset - 1) || '$' == document.getChar(offset - 1))) { return true; } } } catch (BadLocationException e) { JspEditorPlugin.getPluginLog().logError(e); } return false; } public static ELInfoHoverBrowserInformationControlInput getHoverInfo2Internal(IJavaElement[] elements, boolean useFullHTML) { int nResults= elements.length; StringBuffer buffer= new StringBuffer(); boolean hasContents= false; String base= null; IJavaElement element= null; int leadingImageWidth= 0; if (nResults > 1) { for (int i= 0; i < elements.length; i++) { if (useFullHTML) { HTMLPrinter.startBulletList(buffer); } if (elements[i] == null) continue; if (elements[i] instanceof IMember || elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE || elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) { if (useFullHTML) { HTMLPrinter.addBullet(buffer, getInfoText(elements[i], false, useFullHTML)); } else { buffer.append('\u002d').append(' ').append(getInfoText(elements[i], false, useFullHTML)); } hasContents= true; } if (useFullHTML) { HTMLPrinter.endBulletList(buffer); } else { buffer.append("<br/>"); //$NON-NLS-1$ } } for (int i=0; i < elements.length; i++) { if (elements[i] == null) continue; if (elements[i] instanceof IMember || elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE || elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) { if (!useFullHTML) { buffer.append("<br/>"); //$NON-NLS-1$ } base = addFullInfo(buffer, elements[i], useFullHTML); hasContents = true; } } } else { element= elements[0]; if (element instanceof IMember || element.getElementType() == IJavaElement.LOCAL_VARIABLE || element.getElementType() == IJavaElement.TYPE_PARAMETER) { base = addFullInfo(buffer, element, useFullHTML); hasContents= true; } leadingImageWidth= 20; } if (!hasContents) return null; if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0, useFullHTML ? getStyleSheet() : null); if (base != null) { int endHeadIdx= buffer.indexOf("</head>"); //$NON-NLS-1$ if (endHeadIdx != -1) { buffer.insert(endHeadIdx, "\n<base href='" + base + "'>\n"); //$NON-NLS-1$ //$NON-NLS-2$ } } HTMLPrinter.addPageEpilog(buffer); return new ELInfoHoverBrowserInformationControlInput(null, elements, buffer.toString(), leadingImageWidth); } return null; } /** * Adds full information to the hover * Returns base URL if exists * * @param buffer * @param element * @return */ private static String addFullInfo(StringBuffer buffer, IJavaElement element, boolean useFullHTML) { String base= null; if (element instanceof IMember) { IMember member= (IMember) element; HTMLPrinter.addSmallHeader(buffer, getInfoText(member, true, useFullHTML)); Reader reader; try { String content= JavadocContentAccess2.getHTMLContent(member, true); reader= content == null ? null : new StringReader(content); // Provide hint why there's no Javadoc if (reader == null && member.isBinary()) { boolean hasAttachedJavadoc= JavaDocLocations.getJavadocBaseLocation(member) != null; IPackageFragmentRoot root= (IPackageFragmentRoot)member.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); boolean hasAttachedSource= root != null && root.getSourceAttachmentPath() != null; IOpenable openable= member.getOpenable(); boolean hasSource= openable.getBuffer() != null; if (!hasAttachedSource && !hasAttachedJavadoc) reader= new StringReader(ELInfoHoverMessages.ELInfoHover_noAttachments); else if (!hasAttachedJavadoc && !hasSource) reader= new StringReader(ELInfoHoverMessages.ELInfoHover_noAttachedJavadoc); else if (!hasAttachedSource) reader= new StringReader(ELInfoHoverMessages.ELInfoHover_noAttachedJavaSource); else if (!hasSource) reader= new StringReader(ELInfoHoverMessages.ELInfoHover_noInformation); } else { base= JavaDocLocations.getBaseURL(member); } } catch (JavaModelException ex) { reader= new StringReader(ELInfoHoverMessages.ELInfoHover_error_gettingJavadoc); JavaPlugin.log(ex); } if (reader != null) { HTMLPrinter.addParagraph(buffer, reader); } } else if (element.getElementType() == IJavaElement.LOCAL_VARIABLE || element.getElementType() == IJavaElement.TYPE_PARAMETER) { HTMLPrinter.addSmallHeader(buffer, getInfoText(element, true, useFullHTML)); } return base; } private static final long LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS | JavaElementLabels.F_PRE_TYPE_SIGNATURE | JavaElementLabels.M_PRE_TYPE_PARAMETERS | JavaElementLabels.T_TYPE_PARAMETERS | JavaElementLabels.USE_RESOLVED; private static final long LOCAL_VARIABLE_FLAGS= LABEL_FLAGS & ~JavaElementLabels.F_FULLY_QUALIFIED | JavaElementLabels.F_POST_QUALIFIED; private static final long TYPE_PARAMETER_FLAGS= LABEL_FLAGS | JavaElementLabels.TP_POST_QUALIFIED; private static String getInfoText(IJavaElement element, boolean allowImage, boolean useFullHTML) { long flags; switch (element.getElementType()) { case IJavaElement.LOCAL_VARIABLE: flags= LOCAL_VARIABLE_FLAGS; break; case IJavaElement.TYPE_PARAMETER: flags= TYPE_PARAMETER_FLAGS; break; default: flags= LABEL_FLAGS; break; } StringBuffer label= new StringBuffer(JavaElementLinks.getElementLabel(element, flags)); String imageName= null; if (allowImage) { URL imageUrl= JavaPlugin.getDefault().getImagesOnFSRegistry().getImageURL(element); if (imageUrl != null) { imageName= imageUrl.toExternalForm(); } } StringBuffer buf= new StringBuffer(); addImageAndLabel(buf, imageName, 16, 16, 2, 2, label.toString(), 2, 2, useFullHTML); return buf.toString(); } /** * The style sheet (css). * @since 3.4 */ private static String fgStyleSheet; /** * Returns the Javadoc hover style sheet with the current Javadoc font from the preferences. * @return the updated style sheet * @since 3.4 */ private static String getStyleSheet() { if (fgStyleSheet == null) fgStyleSheet= loadStyleSheet(); String css= fgStyleSheet; if (css != null) { FontData fontData= JFaceResources.getFontRegistry().getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0]; css= HTMLPrinter.convertTopLevelFont(css, fontData); } return css; } /** * Loads and returns the Javadoc hover style sheet. * @return the style sheet, or <code>null</code> if unable to load * @since 3.4 */ private static String loadStyleSheet() { Bundle bundle= Platform.getBundle(JavaPlugin.getPluginId()); URL styleSheetURL= bundle.getEntry("/JavadocHoverStyleSheet.css"); //$NON-NLS-1$ if (styleSheetURL != null) { BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(styleSheetURL.openStream())); StringBuffer buffer= new StringBuffer(1500); String line= reader.readLine(); while (line != null) { buffer.append(line); buffer.append('\n'); line= reader.readLine(); } return buffer.toString(); } catch (IOException ex) { JavaPlugin.log(ex); return ""; //$NON-NLS-1$ } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } return null; } public static void addImageAndLabel(StringBuffer buf, String imageName, int imageWidth, int imageHeight, int imageLeft, int imageTop, String label, int labelLeft, int labelTop, boolean useFullHTML) { if (imageName != null) { StringBuffer imageStyle= new StringBuffer("position: relative; "); //$NON-NLS-1$ imageStyle.append("width: ").append(imageWidth).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ imageStyle.append("height: ").append(imageHeight).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ if (imageTop != -1) imageStyle.append("top: ").append(imageTop).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ if (imageLeft != -1) imageStyle.append("left: ").append(imageLeft).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ if (useFullHTML) { buf.append("<!--[if lte IE 6]><![if gte IE 5.5]>\n"); //$NON-NLS-1$ buf.append("<span style=\"").append(imageStyle).append("filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='").append(imageName).append("')\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<![endif]><![endif]-->\n"); //$NON-NLS-1$ buf.append("<!--[if !IE]>-->\n"); //$NON-NLS-1$ buf.append("<img style='").append(imageStyle).append("' src='").append(imageName).append("'>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<!--<![endif]-->\n"); //$NON-NLS-1$ buf.append("<!--[if gte IE 7]>\n"); //$NON-NLS-1$ buf.append("<img style='").append(imageStyle).append("' src='").append(imageName).append("'>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<![endif]-->\n"); //$NON-NLS-1$ } else { buf.append("<img style='").append(imageStyle).append("' src='").append(imageName).append("'>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } buf.append("<span style='word-wrap:break-word;"); //$NON-NLS-1$ if (imageName != null) { buf.append("margin-left: ").append(labelLeft).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ buf.append("margin-top: ").append(labelTop).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ } buf.append("'>"); //$NON-NLS-1$ buf.append(label); buf.append("</span>"); //$NON-NLS-1$ if (imageName != null) { buf.append("</span>"); //$NON-NLS-1$ } } } @SuppressWarnings("restriction") class ELInfoHoverBrowserInformationControlInput extends BrowserInformationControlInput { private final IJavaElement[] fElements; private final String fHtml; private final int fLeadingImageWidth; /** * Creates a new browser information control input. * * @param previous previous input, or <code>null</code> if none available * @param element the element, or <code>null</code> if none available * @param html HTML contents, must not be null * @param leadingImageWidth the indent required for the element image */ public ELInfoHoverBrowserInformationControlInput(BrowserInformationControlInput previous, IJavaElement[] elements, String html, int leadingImageWidth) { super(previous); Assert.isNotNull(html); fElements= elements; fHtml= html; fLeadingImageWidth= leadingImageWidth; } /* * @see org.eclipse.jface.internal.text.html.BrowserInformationControlInput#getLeadingImageWidth() * @since 3.4 */ public int getLeadingImageWidth() { return fLeadingImageWidth; } /** * Returns the Java element. * * @return the element or <code>null</code> if none available */ public IJavaElement[] getElements() { return fElements; } /* * @see org.eclipse.jface.internal.text.html.BrowserInput#getHtml() */ public String getHtml() { return fHtml; } @Override public Object getInputElement() { return fElements == null ? (Object) fHtml : fElements; } private String fInputName = null; @Override public String getInputName() { if (fInputName != null) return fInputName; String inputName = ""; //$NON-NLS-1$ for (int i = 0; fElements != null && i < fElements.length; i++) { if (i > 0 && inputName.trim().length() > 0) inputName += " & "; //$NON-NLS-1$ inputName += fElements[i].getElementName(); } fInputName = inputName; return fInputName; } }
true
true
public Object getHoverInfo2(ITextViewer textViewer, IRegion region) { // find a region of __java_string, if we're in it - use it IDocument document = textViewer == null ? null : textViewer.getDocument(); if (document == null) return null; int rangeStart = -1; int rangeLength = 0; IToken rangeToken = null; FastJavaPartitionScanner scanner = new FastJavaPartitionScanner(); scanner.setRange(document, 0, document.getLength()); while(true) { IToken token = scanner.nextToken(); if(token == null || token.isEOF()) break; int start = scanner.getTokenOffset(); int length = scanner.getTokenLength(); int end = start + length; if(start <= region.getOffset() && end >= region.getOffset()) { rangeStart = start; rangeLength = length; rangeToken = token; break; } if(start > region.getOffset()) break; } if (rangeToken == null || rangeStart == -1 || rangeLength <=0 || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData())) return null; // OK. We've found JAVA_STRING token // Check that the position is in the EL if (!checkStartPosition(document, region.getOffset())) return null; // Calculate and prepare KB-query parameters String text = null; try { text = document.get(rangeStart, rangeLength); } catch (BadLocationException e) { JspEditorPlugin.getPluginLog().logError(e); } int inValueOffset = region.getOffset() - rangeStart; ELParser p = ELParserUtil.getJbossFactory().createParser(); ELModel model = p.parse(text); ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression if (ie == null) return null; ITypeRoot input= getEditorInputJavaElement(); if (input == null) return null; IResource r = input.getResource(); if(!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) { //$NON-NLS-1$ return null; } IFile file = (IFile)r; ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE); ELResolver[] resolvers = context.getElResolvers(); for (int i = 0; resolvers != null && i < resolvers.length; i++) { ELResolution resolution = resolvers[i] == null ? null : resolvers[i].resolve(context, ie, region.getOffset() + region.getLength()); if (resolution == null) continue; ELSegment segment = resolution.getLastSegment(); if (!segment.isResolved()) continue; if(segment instanceof JavaMemberELSegmentImpl) { JavaMemberELSegmentImpl jmSegment = (JavaMemberELSegmentImpl)segment; IJavaElement[] javaElements = jmSegment.getAllJavaElements(); if (javaElements == null || javaElements.length == 0) { if (jmSegment.getJavaElement() == null) continue; javaElements = new IJavaElement[] {jmSegment.getJavaElement()}; } if (javaElements == null || javaElements.length == 0) continue; return JavaStringELInfoHover.getHoverInfo2Internal(javaElements, true); } else if (segment instanceof MessagePropertyELSegmentImpl) { MessagePropertyELSegmentImpl mpSegment = (MessagePropertyELSegmentImpl)segment; String baseName = mpSegment.getBaseName(); String propertyName = mpSegment.isBundle() ? null : StringUtil.trimQuotes(segment.getToken().getText()); String hoverText = ELProposalProcessor.getELMessagesHoverInternal(baseName, propertyName, (List<XModelObject>)mpSegment.getObjects()); StringBuffer buffer = new StringBuffer(hoverText); HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet()); HTMLPrinter.addPageEpilog(buffer); return new ELInfoHoverBrowserInformationControlInput(null, new IJavaElement[0], buffer.toString(), 0); } } return null; }
public Object getHoverInfo2(ITextViewer textViewer, IRegion region) { // find a region of __java_string, if we're in it - use it IDocument document = textViewer == null ? null : textViewer.getDocument(); if (document == null) return null; int rangeStart = -1; int rangeLength = 0; IToken rangeToken = null; FastJavaPartitionScanner scanner = new FastJavaPartitionScanner(); scanner.setRange(document, 0, document.getLength()); while(true) { IToken token = scanner.nextToken(); if(token == null || token.isEOF()) break; int start = scanner.getTokenOffset(); int length = scanner.getTokenLength(); int end = start + length; if(start <= region.getOffset() && end >= region.getOffset()) { rangeStart = start; rangeLength = length; rangeToken = token; break; } if(start > region.getOffset()) break; } if (rangeToken == null || rangeStart == -1 || rangeLength <=0 || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData())) return null; // OK. We've found JAVA_STRING token // Check that the position is in the EL if (!checkStartPosition(document, region.getOffset())) return null; // Calculate and prepare KB-query parameters String text = null; try { text = document.get(rangeStart, rangeLength); } catch (BadLocationException e) { JspEditorPlugin.getPluginLog().logError(e); } int inValueOffset = region.getOffset() - rangeStart; ELParser p = ELParserUtil.getJbossFactory().createParser(); ELModel model = p.parse(text); ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression if (ie == null) return null; ITypeRoot input= getEditorInputJavaElement(); if (input == null) return null; IResource r = input.getResource(); if(!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) { //$NON-NLS-1$ return null; } IFile file = (IFile)r; ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE); ELResolver[] resolvers = context.getElResolvers(); for (int i = 0; resolvers != null && i < resolvers.length; i++) { ELResolution resolution = resolvers[i] == null ? null : resolvers[i].resolve(context, ie, region.getOffset() + region.getLength()); if (resolution == null) continue; ELSegment segment = resolution.getLastSegment(); if (segment==null || !segment.isResolved()) continue; if(segment instanceof JavaMemberELSegmentImpl) { JavaMemberELSegmentImpl jmSegment = (JavaMemberELSegmentImpl)segment; IJavaElement[] javaElements = jmSegment.getAllJavaElements(); if (javaElements == null || javaElements.length == 0) { if (jmSegment.getJavaElement() == null) continue; javaElements = new IJavaElement[] {jmSegment.getJavaElement()}; } if (javaElements == null || javaElements.length == 0) continue; return JavaStringELInfoHover.getHoverInfo2Internal(javaElements, true); } else if (segment instanceof MessagePropertyELSegmentImpl) { MessagePropertyELSegmentImpl mpSegment = (MessagePropertyELSegmentImpl)segment; String baseName = mpSegment.getBaseName(); String propertyName = mpSegment.isBundle() ? null : StringUtil.trimQuotes(segment.getToken().getText()); String hoverText = ELProposalProcessor.getELMessagesHoverInternal(baseName, propertyName, (List<XModelObject>)mpSegment.getObjects()); StringBuffer buffer = new StringBuffer(hoverText); HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet()); HTMLPrinter.addPageEpilog(buffer); return new ELInfoHoverBrowserInformationControlInput(null, new IJavaElement[0], buffer.toString(), 0); } } return null; }
diff --git a/src/org/ohmage/request/survey/SurveyResponseReadRequest.java b/src/org/ohmage/request/survey/SurveyResponseReadRequest.java index 846adc88..ea89d2e9 100644 --- a/src/org/ohmage/request/survey/SurveyResponseReadRequest.java +++ b/src/org/ohmage/request/survey/SurveyResponseReadRequest.java @@ -1,1675 +1,1679 @@ package org.ohmage.request.survey; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.domain.Location; import org.ohmage.domain.campaign.Campaign; import org.ohmage.domain.campaign.Prompt; import org.ohmage.domain.campaign.PromptResponse; import org.ohmage.domain.campaign.RepeatableSet; import org.ohmage.domain.campaign.RepeatableSetResponse; import org.ohmage.domain.campaign.Response; import org.ohmage.domain.campaign.Survey; import org.ohmage.domain.campaign.SurveyItem; import org.ohmage.domain.campaign.SurveyResponse; import org.ohmage.domain.campaign.SurveyResponse.ColumnKey; import org.ohmage.domain.campaign.SurveyResponse.OutputFormat; import org.ohmage.domain.campaign.SurveyResponse.SortParameter; import org.ohmage.exception.ServiceException; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.UserRequest; import org.ohmage.service.CampaignServices; import org.ohmage.service.SurveyResponseReadServices; import org.ohmage.service.SurveyResponseServices; import org.ohmage.service.UserCampaignServices; import org.ohmage.util.DateUtils; import org.ohmage.util.TimeUtils; import org.ohmage.validator.CampaignValidators; import org.ohmage.validator.SurveyResponseValidators; /** * <p>Allows a requester to read survey responses. Supervisors can read survey * responses anytime. Survey response owners (i.e., participants) can read * their own responses anytime. Authors can only read shared responses. * Analysts can read shared responses only if the campaign is shared.</p> * <table border="1"> * <tr> * <td>Parameter Name</td> * <td>Description</td> * <td>Required</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#AUTH_TOKEN}</td> * <td>The requesting user's authentication token.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CLIENT}</td> * <td>A string describing the client that is making this request.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CAMPAIGN_URN}</td> * <td>The campaign URN to use when retrieving responses.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#USER_LIST}</td> * <td>A comma-separated list of usernames to retrieve responses for * or the value {@value URN_SPECIAL_ALL}</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#COLUMN_LIST}</td> * <td>A comma-separated list of the columns to retrieve responses for * or the value {@value #_URN_SPECIAL_ALL}. If {@value #_URN_SPECIAL_ALL} * is not used, the only allowed values are: * {@value org.ohmage.domain.campaign.SurveyResponse.ColumnKey#URN_CONTEXT_CLIENT}, * {@value #URN_CONTEXT_TIMESTAMP}, * {@value #URN_CONTEXT_TIMEZONE}, * {@value #URN_CONTEXT_UTC_TIMESTAMP}, * {@value #URN_CONTEXT_LAUNCH_CONTEXT_LONG}, * {@value #URN_CONTEXT_LAUNCH_CONTEXT_SHORT}, * {@value #URN_CONTEXT_LOCATION_STATUS}, * {@value #URN_CONTEXT_LOCATION_LONGITUDE}, * {@value #URN_CONTEXT_LOCATION_LATITUDE}, * {@value #URN_CONTEXT_LOCATION_TIMESTAMP}, * {@value #URN_CONTEXT_LOCATION_ACCURACY}, * {@value #URN_CONTEXT_LOCATION_PROVIDER}, * {@value #URN_USER_ID}, * {@value #URN_SURVEY_ID}, * {@value #URN_SURVEY_TITLE}, * {@value #URN_SURVEY_DESCRIPTION}, * {@value #URN_SURVEY_PRIVACY_STATE}, * {@value #URN_REPEATABLE_SET_ID}, * {@value #URN_REPEATABLE_SET_ITERATION}, * {@value #URN_PROMPT_RESPONSE} * </td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#OUTPUT_FORMAT}</td> * <td>The desired output format of the results. Must be one of * {@value #_OUTPUT_FORMAT_JSON_ROWS}, {@value #_OUTPUT_FORMAT_JSON_COLUMNS}, * or, {@value #_OUTPUT_FORMAT_CSV}</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PROMPT_ID_LIST}</td> * <td>A comma-separated list of prompt ids to retrieve responses for * or the value {@link #_URN_SPECIAL_ALL}. This key is only * optional if {@value org.ohmage.request.InputKeys#SURVEY_ID_LIST} * is not present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SURVEY_ID_LIST}</td> * <td>A comma-separated list of survey ids to retrieve responses for * or the value {@link #_URN_SPECIAL_ALL}. This key is only * optional if {@value org.ohmage.request.InputKeys#PROMPT_ID_LIST} * is not present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#START_DATE}</td> * <td>The start date to use for results between dates. * Required if end date is present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#END_DATE}</td> * <td>The end date to use for results between dates. * Required if start date is present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SORT_ORDER}</td> * <td>The sort order to use i.e., the SQL order by.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SUPPRESS_METADATA}</td> * <td>For {@value #_OUTPUT_FORMAT_CSV} output, whether to suppress the * metadata section from the output</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PRETTY_PRINT}</td> * <td>For JSON-based output, whether to pretty print the output</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#RETURN_ID}</td> * <td>For {@value #_OUTPUT_FORMAT_JSON_ROWS} output, whether to return * the id on each result. The web front-end uses the id value to perform * updates.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PRIVACY_STATE}</td> * <td>Filters the results by their associated privacy state.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#COLLAPSE}</td> * <td>Filters the results by uniqueness.</td> * <td>false</td> * </tr> * </table> * * @author Joshua Selsky */ public final class SurveyResponseReadRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(SurveyResponseReadRequest.class); /** * The JSON key for the metadata associated with a response read request. */ public static final String JSON_KEY_METADATA = "metadata"; /** * The, optional, additional JSON key associated with a prompt responses in * the * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS JSON_COLUMNS} * format representing additional information about the prompt's responses. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS */ public static final String JSON_KEY_CONTEXT = "context"; /** * The JSON key associated with a prompt responses in the * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS JSON_COLUMNS} * format representing the values for the prompt response. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS */ public static final String JSON_KEY_VALUES = "values"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * representing the number of unique surveys in the results. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_NUM_SURVEYS = "number_of_surveys"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * representing the number of unique prompts in the results. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_NUM_PROMPTS = "number_of_prompts"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * output representing the keys in the data portion of the response. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_ITEMS = "items"; /** * The JSON key associated with every record if the input parameter * {@link org.ohmage.request.InputKeys#COLLAPSE collapse} is true. * * @see org.ohmage.request.InputKeys#COLLAPSE */ public static final String JSON_KEY_COUNT = "count"; public static final String URN_SPECIAL_ALL = "urn:ohmage:special:all"; public static final Collection<String> URN_SPECIAL_ALL_LIST; static { URN_SPECIAL_ALL_LIST = new HashSet<String>(); URN_SPECIAL_ALL_LIST.add(URN_SPECIAL_ALL); } private static final int MAX_NUMBER_OF_USERS = 10; private static final int MAX_NUMBER_OF_SURVEYS = 10; private static final int MAX_NUMBER_OF_PROMPTS = 10; private final String campaignId; private final Collection<SurveyResponse.ColumnKey> columns; private final Collection<String> usernames; private final SurveyResponse.OutputFormat outputFormat; private final Collection<String> surveyIds; private final Collection<String> promptIds; private final Date startDate; private final Date endDate; private final List<SortParameter> sortOrder; private final SurveyResponse.PrivacyState privacyState; private final Boolean collapse; private final Boolean prettyPrint; private final Boolean returnId; private final Boolean suppressMetadata; private Campaign campaign; private List<SurveyResponse> surveyResponseList; /** * Creates a survey response read request. * * @param httpRequest The request to retrieve parameters from. */ public SurveyResponseReadRequest(HttpServletRequest httpRequest) { // Handle user-password or token-based authentication super(httpRequest, TokenLocation.EITHER, false); String tCampaignId = null; Set<SurveyResponse.ColumnKey> tColumns = null; Set<String> tUsernames = null; SurveyResponse.OutputFormat tOutputFormat = null; Set<String> tSurveyIds = null; Set<String> tPromptIds = null; Date tStartDate = null; Date tEndDate = null; List<SortParameter> tSortOrder = null; SurveyResponse.PrivacyState tPrivacyState = null; Boolean tCollapse = null; Boolean tPrettyPrint = null; Boolean tReturnId = null; Boolean tSuppressMetadata = null; if(! isFailed()) { LOGGER.info("Creating a survey response read request."); String[] t; try { // Campaign ID t = getParameterValues(InputKeys.CAMPAIGN_URN); if(t.length == 0) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); } else if(t.length > 1) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "Multiple campaign IDs were found: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("Multiple campaign IDs were found: " + InputKeys.CAMPAIGN_URN); } else { tCampaignId = CampaignValidators.validateCampaignId(t[0]); if(tCampaignId == null) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); } } // Column List t = getParameterValues(InputKeys.COLUMN_LIST); if(t.length == 0) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); throw new ValidationException("The required column list was missing: " + InputKeys.COLUMN_LIST); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "Multiple column lists were given: " + InputKeys.COLUMN_LIST); throw new ValidationException("Multiple column lists were given: " + InputKeys.COLUMN_LIST); } else { tColumns = SurveyResponseValidators.validateColumnList(t[0]); if(tColumns == null) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); throw new ValidationException("The required column list was missing: " + InputKeys.COLUMN_LIST); } } // User List t = getParameterValues(InputKeys.USER_LIST); if(t.length == 0) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "The user list is missing: " + InputKeys.USER_LIST); throw new ValidationException("The user list is missing: " + InputKeys.USER_LIST); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "Mutliple user lists were given: " + InputKeys.USER_LIST); throw new ValidationException("Mutliple user lists were given: " + InputKeys.USER_LIST); } else { tUsernames = SurveyResponseValidators.validateUsernames(t[0]); if(tUsernames == null) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "The user list is missing: " + InputKeys.USER_LIST); throw new ValidationException("The user list is missing: " + InputKeys.USER_LIST); } else if(tUsernames.size() > MAX_NUMBER_OF_USERS) { setFailed(ErrorCode.SURVEY_TOO_MANY_USERS, "The user list contains more than " + MAX_NUMBER_OF_USERS + " users: " + tUsernames.size()); throw new ValidationException("The user list contains more than " + MAX_NUMBER_OF_USERS + " users: " + tUsernames.size()); } } // Output Format t = getParameterValues(InputKeys.OUTPUT_FORMAT); if(t.length == 0) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("The output format is missing: " + InputKeys.OUTPUT_FORMAT); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "Multiple output formats were given: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("Multiple output formats were given: " + InputKeys.OUTPUT_FORMAT); } else { tOutputFormat = SurveyResponseValidators.validateOutputFormat(t[0]); if(tOutputFormat == null) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("The output format is missing: " + InputKeys.OUTPUT_FORMAT); } } // Survey ID List t = getParameterValues(InputKeys.SURVEY_ID_LIST); if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_SURVEY_ID_LIST, "Multiple survey ID lists were given: " + InputKeys.SURVEY_ID_LIST); throw new ValidationException("Multiple survey ID lists were given: " + InputKeys.SURVEY_ID_LIST); } else if(t.length == 1) { tSurveyIds = SurveyResponseValidators.validateSurveyIds(t[0]); if((tSurveyIds != null) && (tSurveyIds.size() > MAX_NUMBER_OF_SURVEYS)) { setFailed(ErrorCode.SURVEY_TOO_MANY_SURVEY_IDS, "More than " + MAX_NUMBER_OF_SURVEYS + " survey IDs were given: " + tSurveyIds.size()); throw new ValidationException("More than " + MAX_NUMBER_OF_SURVEYS + " survey IDs were given: " + tSurveyIds.size()); } } // Prompt ID List t = getParameterValues(InputKeys.PROMPT_ID_LIST); if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_PROMPT_ID_LIST, "Multiple prompt ID lists were given: " + InputKeys.PROMPT_ID_LIST); throw new ValidationException("Multiple prompt ID lists were given: " + InputKeys.PROMPT_ID_LIST); } else if(t.length == 1) { tPromptIds = SurveyResponseValidators.validatePromptIds(t[0]); if((tPromptIds != null) && (tPromptIds.size() > MAX_NUMBER_OF_PROMPTS)) { setFailed(ErrorCode.SURVEY_TOO_MANY_PROMPT_IDS, "More than " + MAX_NUMBER_OF_PROMPTS + " prompt IDs were given: " + tPromptIds.size()); throw new ValidationException("More than " + MAX_NUMBER_OF_PROMPTS + " prompt IDs were given: " + tPromptIds.size()); } } // Survey ID List and Prompt ID List Presence Check if(((tSurveyIds == null) || (tSurveyIds.size() == 0)) && ((tPromptIds == null) || (tPromptIds.size() == 0))) { setFailed(ErrorCode.SURVEY_SURVEY_LIST_OR_PROMPT_LIST_ONLY, "A survey list (" + InputKeys.SURVEY_ID_LIST + ") or a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); throw new ValidationException("A survey list (" + InputKeys.SURVEY_ID_LIST + ") or prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); } else if(((tSurveyIds != null) && (tSurveyIds.size() > 0)) && ((tPromptIds != null) && (tPromptIds.size() > 0))) { setFailed(ErrorCode.SURVEY_SURVEY_LIST_OR_PROMPT_LIST_ONLY, "Both a survey list (" + InputKeys.SURVEY_ID_LIST + ") and a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); throw new ValidationException("Both a survey list (" + InputKeys.SURVEY_ID_LIST + ") and a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); } // Start Date t = getParameterValues(InputKeys.START_DATE); if(t.length > 1) { setFailed(ErrorCode.SERVER_INVALID_DATE, "Multiple start dates were given: " + InputKeys.START_DATE); throw new ValidationException("Multiple start dates were given: " + InputKeys.START_DATE); } else if(t.length == 1) { tStartDate = SurveyResponseValidators.validateStartDate(t[0]); } // End Date t = getParameterValues(InputKeys.END_DATE); if(t.length > 1) { setFailed(ErrorCode.SERVER_INVALID_DATE, "Multiple end dates were given: " + InputKeys.END_DATE); throw new ValidationException("Multiple end dates were given: " + InputKeys.END_DATE); } else if(t.length == 1) { tEndDate = SurveyResponseValidators.validateEndDate(t[0]); } // Sort Order t = getParameterValues(InputKeys.SORT_ORDER); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_SORT_ORDER, "Multiple sort order lists were given: " + InputKeys.SORT_ORDER); throw new ValidationException("Multiple sort order lists were given: " + InputKeys.SORT_ORDER); } else if(t.length == 1) { tSortOrder = SurveyResponseValidators.validateSortOrder(t[0]); } // Privacy State t = getParameterValues(InputKeys.PRIVACY_STATE); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_PRIVACY_STATE, "Multiple privacy state values were given: " + InputKeys.PRIVACY_STATE); throw new ValidationException("Multiple privacy state values were given: " + InputKeys.PRIVACY_STATE); } else if(t.length == 1) { tPrivacyState = SurveyResponseValidators.validatePrivacyState(t[0]); } // Collapse t = getParameterValues(InputKeys.COLLAPSE); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_COLLAPSE_VALUE, "Multiple collapse values were given: " + InputKeys.COLLAPSE); throw new ValidationException("Multiple collapse values were given: " + InputKeys.COLLAPSE); } else if(t.length == 1) { tCollapse = SurveyResponseValidators.validateCollapse(t[0]); } // Pretty print t = getParameterValues(InputKeys.PRETTY_PRINT); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_PRETTY_PRINT_VALUE, "Multiple pretty print values were given: " + InputKeys.PRETTY_PRINT); throw new ValidationException("Multiple pretty print values were given: " + InputKeys.PRETTY_PRINT); } else if(t.length == 1) { tPrettyPrint = SurveyResponseValidators.validatePrettyPrint(t[0]); } // Return ID t = getParameterValues(InputKeys.RETURN_ID); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_RETURN_ID, "Multiple return ID values were given: " + InputKeys.RETURN_ID); throw new ValidationException("Multiple return ID values were given: " + InputKeys.RETURN_ID); } else if(t.length == 1) { tReturnId = SurveyResponseValidators.validateReturnId(t[0]); } // Suppress metadata t = getParameterValues(InputKeys.SUPPRESS_METADATA); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_SUPPRESS_METADATA_VALUE, "Multiple suppress metadata values were given: " + InputKeys.SUPPRESS_METADATA); throw new ValidationException("Multiple suppress metadata values were given: " + InputKeys.SUPPRESS_METADATA); } else if(t.length == 1) { tSuppressMetadata = SurveyResponseValidators.validateSuppressMetadata(t[0]); } } catch (ValidationException e) { e.failRequest(this); LOGGER.info(e); } } campaignId = tCampaignId; columns = tColumns; usernames = tUsernames; outputFormat = tOutputFormat; surveyIds = tSurveyIds; promptIds = tPromptIds; startDate = tStartDate; endDate = tEndDate; sortOrder = tSortOrder; privacyState = tPrivacyState; collapse = tCollapse; prettyPrint = tPrettyPrint; returnId = tReturnId; suppressMetadata = tSuppressMetadata; } /** * Services this request. */ @Override public void service() { LOGGER.info("Servicing a survey response read request."); if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } try { // This is not necessarily the case because the user may no longer // belong to the campaign but still want to see their data. This // should only check that the campaign exists. LOGGER.info("Verifying that requester belongs to the campaign specified by campaign ID."); UserCampaignServices.instance().campaignExistsAndUserBelongs(campaignId, this.getUser().getUsername()); // We have removed this ACL check because it causes participants // to not be able to view their own data. The bigger problem // is that for "Browse Data" the front end always passes // user_list=urn:ohmage:special:all // LOGGER.info("Verifying that the requester has a role that allows reading of survey responses for each of the users in the list."); // UserCampaignServices.requesterCanViewUsersSurveyResponses(this, this.campaignUrn, this.getUser().getUsername(), (String[]) userList.toArray()); // The user may want to read survey responses from a user that no // longer belongs to the campaign. if(! usernames.equals(URN_SPECIAL_ALL_LIST)) { LOGGER.info("Checking the user list to make sure all of the users belong to the campaign ID."); UserCampaignServices.instance().verifyUsersExistInCampaign(campaignId, usernames); } LOGGER.info("Retrieving campaign configuration."); campaign = CampaignServices.instance().getCampaign(campaignId); if((promptIds != null) && (! promptIds.isEmpty()) && (! URN_SPECIAL_ALL_LIST.equals(promptIds))) { LOGGER.info("Verifying that the prompt ids in the query belong to the campaign."); SurveyResponseReadServices.instance().verifyPromptIdsBelongToConfiguration(promptIds, campaign); } if((surveyIds != null) && (! surveyIds.isEmpty()) && (! URN_SPECIAL_ALL_LIST.equals(surveyIds))) { LOGGER.info("Verifying that the survey ids in the query belong to the campaign."); SurveyResponseReadServices.instance().verifySurveyIdsBelongToConfiguration(surveyIds, campaign); } LOGGER.info("Dispatching to the data layer."); surveyResponseList = SurveyResponseServices.instance().readSurveyResponseInformation( campaign, (URN_SPECIAL_ALL_LIST.equals(usernames) ? null : usernames), null, startDate, endDate, privacyState, (URN_SPECIAL_ALL_LIST.equals(surveyIds)) ? null : surveyIds, (URN_SPECIAL_ALL_LIST.equals(promptIds)) ? null : promptIds, null ); LOGGER.info("Found " + surveyResponseList.size() + " results"); LOGGER.info("Filtering survey response results according to our privacy rules and the requester's role."); SurveyResponseReadServices.instance().performPrivacyFilter(this.getUser().getUsername(), campaignId, surveyResponseList); LOGGER.info("Found " + surveyResponseList.size() + " results after filtering."); if(sortOrder != null) { LOGGER.info("Sorting the results."); Collections.sort( surveyResponseList, new Comparator<SurveyResponse>() { @Override public int compare( SurveyResponse o1, SurveyResponse o2) { for(SortParameter sortParameter : sortOrder) { switch(sortParameter) { case SURVEY: if(! o1.getSurvey().equals(o2.getSurvey())) { return o1.getSurvey().getId().compareTo(o2.getSurvey().getId()); } break; case TIMESTAMP: if(o1.getTime() != o2.getTime()) { if((o1.getTime() - o2.getTime()) < 0) { return -1; } else { return 1; } } break; case USER: if(! o1.getUsername().equals(o2.getUsername())) { return o1.getUsername().compareTo(o2.getUsername()); } break; } } return 0; } } ); } } catch(ServiceException e) { e.failRequest(this); e.logException(LOGGER); } } /** * Builds the output depending on the state of this request and whatever * output format the requester selected. */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey response read request."); if(isFailed()) { super.respond(httpRequest, httpResponse, null); return; } // Create a writer for the HTTP response object. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse))); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); return; } // Sets the HTTP headers to disable caching. expireResponse(httpResponse); String resultString = ""; if(! isFailed()) { try { boolean allColumns = columns.equals(URN_SPECIAL_ALL_LIST); // TODO: I am fairly confident that these two branches can be // merged further and subsequently cleaned up, but I don't have // the time to tackle it right now. if(OutputFormat.JSON_ROWS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject result = new JSONObject(); result.put(JSON_KEY_RESULT, RESULT_SUCCESS); List<String> uniqueSurveyIds = new LinkedList<String>(); List<String> uniquePromptIds = new LinkedList<String>(); JSONArray results = new JSONArray(); for(SurveyResponse surveyResponse : surveyResponseList) { uniqueSurveyIds.add(surveyResponse.getSurvey().getId()); uniquePromptIds.addAll(surveyResponse.getPromptIds()); JSONObject currResult = surveyResponse.toJson( allColumns || columns.contains(ColumnKey.USER_ID), allColumns || false, allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT), allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE), allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS), allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE), allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS), false, allColumns || columns.contains(ColumnKey.SURVEY_ID), allColumns || columns.contains(ColumnKey.SURVEY_TITLE), allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG), allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE), false, ((returnId == null) ? false : returnId) ); if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { currResult.put( "timestamp", TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { currResult.put( "utc_timestamp", DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { double accuracy = location.getAccuracy(); if(Double.isInfinite(accuracy) || Double.isNaN(accuracy)) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_ACCURACY, accuracy); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { double latitude = location.getLatitude(); if(Double.isInfinite(latitude) || Double.isNaN(latitude)) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LATITUDE, latitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { double longitude = location.getLongitude(); if(Double.isInfinite(longitude) || Double.isNaN(longitude)) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LONGITUDE, longitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_PROVIDER, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_PROVIDER, location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME, location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME_ZONE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME_ZONE, location.getTimeZone().getID()); } } results.put(currResult); } if((collapse != null) && collapse) { int numResults = results.length(); Map<JSONObject, Integer> collapsedMap = new HashMap<JSONObject, Integer>(numResults); for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); Integer prevCount = collapsedMap.put(currResult, 1); if(prevCount != null) { collapsedMap.put(currResult, prevCount + 1); results.remove(i); i--; numResults--; } } for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); currResult.put(JSON_KEY_COUNT, collapsedMap.get(currResult)); } } result.put(JSON_KEY_DATA, results); // Metadata if((suppressMetadata == null) || (! suppressMetadata)) { JSONObject metadata = new JSONObject(); metadata.put(JSON_KEY_NUM_SURVEYS, uniqueSurveyIds.size()); metadata.put(JSON_KEY_NUM_PROMPTS, uniquePromptIds.size()); Collection<String> columnsResult = new HashSet<String>(columns.size()); // If it contains the special 'all' value, add them // all. if(columns.contains(URN_SPECIAL_ALL)) { ColumnKey[] values = SurveyResponse.ColumnKey.values(); for(int i = 0; i < values.length; i++) { columnsResult.add(values[i].toString()); } } // Otherwise, add cycle through them else { for(ColumnKey columnKey : columns) { columnsResult.add(columnKey.toString()); } } // Check if prompt responses were requested, and, if // so, add them to the list of columns. if(columns.contains(SurveyResponse.ColumnKey.PROMPT_RESPONSE) || columns.contains(URN_SPECIAL_ALL)) { for(String promptId : uniquePromptIds) { columnsResult.add(ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } } // Add it to the metadata result. metadata.put(JSON_KEY_ITEMS, columnsResult); result.put(JSON_KEY_METADATA, metadata); } if((prettyPrint != null) && prettyPrint) { resultString = result.toString(4); } else { resultString = result.toString(); } } else if(OutputFormat.JSON_COLUMNS.equals(outputFormat) || OutputFormat.CSV.equals(outputFormat)) { JSONArray usernames = new JSONArray(); JSONArray clients = new JSONArray(); JSONArray privacyStates = new JSONArray(); JSONArray timestamps = new JSONArray(); JSONArray utcTimestamps = new JSONArray(); JSONArray epochMillisTimestamps = new JSONArray(); JSONArray timezones = new JSONArray(); JSONArray locationStatuses = new JSONArray(); JSONArray locationLongitude = new JSONArray(); JSONArray locationLatitude = new JSONArray(); JSONArray locationTimestamp = new JSONArray(); JSONArray locationTimeZone = new JSONArray(); JSONArray locationAccuracy = new JSONArray(); JSONArray locationProvider = new JSONArray(); JSONArray surveyIds = new JSONArray(); JSONArray surveyTitles = new JSONArray(); JSONArray surveyDescriptions = new JSONArray(); JSONArray launchContexts = new JSONArray(); Map<String, JSONObject> prompts = new HashMap<String, JSONObject>(); // If the results are empty, then we still want to populate // the resulting JSON with information about all of the // prompts even though they don't have any responses // associated with them. + // FIXME: This shouldn't be conditional on the number of + // responses found. We should create headers for all of the + // requested prompt IDs (either via the list of survey IDs + // or the list of prompt IDs) or none of the prompt IDs if + // prompts aren't requested. if(surveyResponseList.isEmpty()) { // If the user-supplied list of survey IDs is present, if(this.surveyIds != null) { Map<String, Survey> campaignSurveys = campaign.getSurveys(); // If the user asked for all surveys for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // all of the surveys in this campaign. if(this.surveyIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaignSurveys.values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information only // with the data about the requested surveys. else { for(String surveyId : this.surveyIds) { populatePrompts(campaignSurveys.get(surveyId).getSurveyItems(), prompts); } } } // If the user-supplied list of prompt IDs is present, else if(promptIds != null) { // If the user asked for all prompts for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // this campaign. if(this.promptIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaign.getSurveys().values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information with // the data about only the requested prompts. else { int currNumPrompts = 0; Map<Integer, SurveyItem> tempPromptMap = new HashMap<Integer, SurveyItem>(promptIds.size()); for(String promptId : promptIds) { tempPromptMap.put(currNumPrompts, campaign.getPrompt(campaign.getSurveyIdForPromptId(promptId), promptId)); currNumPrompts++; } populatePrompts(tempPromptMap, prompts); } } } // If the results are non-empty, we need to populate the // prompt information only for those prompts to which the // user queried about. else { Set<String> unqiueSurveyIds = new HashSet<String>(); Set<String> uniquePromptIds = new HashSet<String>(); // For each of the survey responses in the result, for(SurveyResponse surveyResponse : surveyResponseList) { String surveyId = surveyResponse.getSurvey().getId(); // If the survey with which this survey response is // associated has not yet been processed, process // it. if(! unqiueSurveyIds.contains(surveyId)) { // Add to the list of surveys that have been // processed so that no subsequent survey // responses that are associated with this // survey cause it to be processed again. unqiueSurveyIds.add(surveyId); // Keep track of the unique number of prompts // that we process. int currNumPrompts = 0; // Get all of the unique prompt IDs for this // survey response. Set<String> promptIds = surveyResponse.getPromptIds(); // Create a a temporary map of Integers to // Prompt objects. Map<Integer, SurveyItem> tempPrompts = new HashMap<Integer, SurveyItem>(promptIds.size()); // Retrieve all of the unique prompts that have // not yet been processed and add them to the // map. for(String promptId : promptIds) { if(! uniquePromptIds.contains(promptId)) { tempPrompts.put(currNumPrompts, campaign.getPrompt(surveyId, promptId)); currNumPrompts++; } } // Populate the prompts JSON with the // information about all of the distinct // prompts from this survey response. populatePrompts(tempPrompts, prompts); } } } // Process each of the survey responses and keep track of // the number of prompt responses. int numSurveyResponses = surveyResponseList.size(); int numPromptResponses = 0; for(SurveyResponse surveyResponse : surveyResponseList) { numPromptResponses += processResponses(allColumns, surveyResponse, surveyResponse.getResponses(), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTimestamp, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } // Add all of the applicable output stuff. JSONObject result = new JSONObject(); // For each of the requested columns, add their respective // data to the result. if(allColumns || columns.contains(ColumnKey.USER_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, usernames); result.put(ColumnKey.USER_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, clients); result.put(ColumnKey.CONTEXT_CLIENT.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, privacyStates); result.put(ColumnKey.SURVEY_PRIVACY_STATE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, utcTimestamps); result.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, epochMillisTimestamps); result.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timezones); result.put(ColumnKey.CONTEXT_TIMEZONE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationStatuses); result.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLongitude); result.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLatitude); result.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { JSONObject timeValues = new JSONObject(); timeValues.put(JSON_KEY_VALUES, locationTimestamp); result.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString(), timeValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMEZONE)) { JSONObject timeZoneValues = new JSONObject(); timeZoneValues.put(JSON_KEY_VALUES, locationTimeZone); result.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString(), timeZoneValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationAccuracy); result.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationProvider); result.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyIds); result.put(ColumnKey.SURVEY_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyTitles); result.put(ColumnKey.SURVEY_TITLE.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyDescriptions); result.put(ColumnKey.SURVEY_DESCRIPTION.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString(), values); } if(columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString(), values); } if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { for(String promptId : prompts.keySet()) { result.put( SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId, prompts.get(promptId)); } } // If the user requested to collapse the results, create a // new column called count and set the initial value for // every existing row to 1. Then, create a map of string // representations of data to their original row. Cycle // through the indices creating a string by concatenating // the value at the given index for each column and // checking the map if the string already exists. If it // does not exist, add the string value and have it point // to the current index. If it does exist, go to that // column, increase the count, and delete this row by // deleting whatever is at the current index in every // column. if((collapse != null) && collapse) { // Get the key for each row. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a new "count" column and initialize every // count to 1. JSONArray counts = new JSONArray(); for(int i = 0; i < numSurveyResponses; i++) { counts.put(1); } JSONObject countObject = new JSONObject(); countObject.put(JSON_KEY_VALUES, counts); result.put("urn:ohmage:context:count", countObject); keys.put("urn:ohmage:context:count"); // Cycle through the responses. Map<String, Integer> valueToIndexMap = new HashMap<String, Integer>(); for(int i = 0; i < numSurveyResponses; i++) { // Build the string. StringBuilder currResultBuilder = new StringBuilder(); for(int j = 0; j < keyLength; j++) { currResultBuilder.append(result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).get(i)); if((j + 1) != keyLength) { currResultBuilder.append(','); } } // Check if the string exists. String currResultString = currResultBuilder.toString(); // If so, go to that index in every column // including the count and delete it, effectively // deleting that row. if(valueToIndexMap.containsKey(currResultString)) { int count = result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).getInt(valueToIndexMap.get(currResultString)) + 1; result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).put(valueToIndexMap.get(currResultString).intValue(), count); for(int j = 0; j < keyLength + 1; j++) { result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).remove(i); } i--; numSurveyResponses--; } // If not, add it to the map. else { valueToIndexMap.put(currResultString, i); } } } // If metadata is not suppressed, create it. JSONObject metadata = null; if((suppressMetadata == null) || (! suppressMetadata)) { metadata = new JSONObject(); metadata.put(InputKeys.CAMPAIGN_URN, campaignId); metadata.put(JSON_KEY_NUM_SURVEYS, surveyResponseList.size()); metadata.put(JSON_KEY_NUM_PROMPTS, numPromptResponses); } if(OutputFormat.JSON_COLUMNS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_SUCCESS); if((suppressMetadata == null) || (! suppressMetadata)) { JSONArray itemsJson = new JSONArray(); Iterator<?> keys = result.keys(); while(keys.hasNext()) { itemsJson.put(keys.next()); } metadata.put("items", itemsJson); resultJson.put(JSON_KEY_METADATA, metadata); } resultJson.put(JSON_KEY_DATA, result); if((prettyPrint != null) && prettyPrint) { resultString = resultJson.toString(4); } else { resultString = resultJson.toString(); } } // For CSV output, else if(OutputFormat.CSV.equals(outputFormat)) { // Mark it as an attachment. httpResponse.setContentType("text/csv"); httpResponse.setHeader( "Content-Disposition", "attachment; filename=SurveyResponses.csv"); StringBuilder resultBuilder = new StringBuilder(); // If the metadata is not suppressed, add it to the // output builder. if((suppressMetadata == null) || (! suppressMetadata)) { metadata.put(JSON_KEY_RESULT, RESULT_SUCCESS); resultBuilder.append("## begin metadata\n"); resultBuilder.append('#').append(metadata.toString().replace(',', ';')).append('\n'); resultBuilder.append("## end metadata\n"); } // Add the prompt contexts to the output builder if // prompts were desired. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { resultBuilder.append("## begin prompt contexts\n"); for(String promptId : prompts.keySet()) { JSONObject promptJson = new JSONObject(); // Use the already-generated JSON from each of // the prompts. promptJson.put( promptId, prompts .get(promptId) - .get(JSON_KEY_CONTEXT) - .toString()); + .get(JSON_KEY_CONTEXT)); resultBuilder .append('#') .append(promptJson.toString()) .append('\n'); } resultBuilder.append("## end prompt contexts\n"); } // Begin the data section of the CSV. resultBuilder.append("## begin data\n"); // We need to get all of the column header names. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a comma-separated list of the header names. resultBuilder.append('#'); for(int i = 0; i < keyLength; i++) { String header = keys.getString(i); if(header.startsWith("urn:ohmage:")) { header = header.substring(11); if(header.startsWith("prompt:id:")) { header = header.substring(10); } } resultBuilder.append(header); if((i + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); // For each of the responses, for(int i = 0; i < numSurveyResponses; i++) { for(int j = 0; j < keyLength; j++) { Object currResult = result .getJSONObject(keys.getString(j)) .getJSONArray(JSON_KEY_VALUES) .get(i); if(JSONObject.NULL.equals(currResult)) { resultBuilder.append(""); } else { resultBuilder.append(currResult); } if((j + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); } resultBuilder.append("## end data"); resultString = resultBuilder.toString(); } } } catch(JSONException e) { LOGGER.error(e.toString(), e); setFailed(); } } if(isFailed()) { httpResponse.setContentType("text/html"); resultString = this.getFailureMessage(); } try { writer.write(resultString); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); } try { writer.flush(); writer.close(); } catch(IOException e) { LOGGER.error("Unable to flush or close the writer.", e); } } /** * Populates the prompts map with all of the prompts from all of the survey * items. * * @param surveyItems The map of survey item indices to the survey item. * * @param prompts The prompts to be populated with all of the prompts in * the survey item including all of the sub-prompts of * repeatable sets. * * @throws JSONException Thrown if there is an error building the JSON. */ private void populatePrompts( final Map<Integer, SurveyItem> surveyItems, Map<String, JSONObject> prompts) throws JSONException { for(SurveyItem surveyItem : surveyItems.values()) { if(surveyItem instanceof Prompt) { Prompt prompt = (Prompt) surveyItem; JSONObject promptJson = new JSONObject(); promptJson.put(JSON_KEY_CONTEXT, prompt.toJson()); promptJson.put(JSON_KEY_VALUES, new JSONArray()); prompts.put(prompt.getId(), promptJson); } else if(surveyItem instanceof RepeatableSet) { RepeatableSet repeatableSet = (RepeatableSet) surveyItem; populatePrompts(repeatableSet.getSurveyItems(), prompts); } } } /** * Processes each of the responses in map to populate the JSONObjects by * placing the value from the response into its corresponding JSONObject. * * @param allColumns Whether or not to populate all JSONObjects. * * @param surveyResponse The current survey response. * * @param responses The map of response index from the survey response to * the actual response. * * @param surveys The map of survey IDs to Survey objects. * * @param prompts The map of prompt IDs to Prompt objects. * * @param usernames The usernames JSONArray. * * @param clients The clients JSONArray. * * @param privacyStates The privacy states JSONArray. * * @param timestamps The timestamps JSONArray. * * @param utcTimestamps The timestamps JSONArray where the timestamps are * converted to UTC. * * @param epochMillisTimestamps The epoch millis JSONArray. * * @param timezones The timezones JSONArray. * * @param locationStatuses The location statuses JSONArray. * * @param locations The locations JSONArray. * * @param surveyIds The survey IDs JSONArray. * * @param surveyTitles The survey titles JSONArray. * * @param surveyDescriptions The survey description JSONArray. * * @param launchContexts The launch contexts JSONArray. * * @return The total number of prompt responses that were processed. * * @throws JSONException Thrown if there is an error populating any of the * JSONArrays. */ private int processResponses(final boolean allColumns, final SurveyResponse surveyResponse, final Map<Integer, Response> responses, Map<String, JSONObject> prompts, JSONArray usernames, JSONArray clients, JSONArray privacyStates, JSONArray timestamps, JSONArray utcTimestamps, JSONArray epochMillisTimestamps, JSONArray timezones, JSONArray locationStatuses, JSONArray locationLongitude, JSONArray locationLatitude, JSONArray locationTime, JSONArray locationTimeZone, JSONArray locationAccuracy, JSONArray locationProvider, JSONArray surveyIds, JSONArray surveyTitles, JSONArray surveyDescriptions, JSONArray launchContexts) throws JSONException { // Add each of the survey response-wide pieces of information. if(allColumns || columns.contains(ColumnKey.USER_ID)) { usernames.put(surveyResponse.getUsername()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { clients.put(surveyResponse.getClient()); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { privacyStates.put(surveyResponse.getPrivacyState().toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { timestamps.put( TimeUtils.getIso8601DateTimeString( new Date( surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { utcTimestamps.put( DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { epochMillisTimestamps.put(surveyResponse.getTime()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { timezones.put(surveyResponse.getTimezone().getID()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { locationStatuses.put(surveyResponse.getLocationStatus().toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { locationLongitude.put(JSONObject.NULL); } else { locationLongitude.put(location.getLongitude()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { locationLatitude.put(JSONObject.NULL); } else { locationLatitude.put(location.getLatitude()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { locationTime.put(JSONObject.NULL); } else { locationTime.put(location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { locationTimeZone.put(JSONObject.NULL); } else { locationTimeZone.put(location.getTimeZone().getID()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { locationAccuracy.put(JSONObject.NULL); } else { locationAccuracy.put(location.getAccuracy()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { locationProvider.put(JSONObject.NULL); } else { locationProvider.put(location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { surveyIds.put(surveyResponse.getSurvey().getId()); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { surveyTitles.put(surveyResponse.getSurvey().getTitle()); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { surveyDescriptions.put(surveyResponse.getSurvey().getDescription()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG) || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { launchContexts.put(surveyResponse.getLaunchContext().toJson(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG))); } int numResponses = 0; // Create a map of which prompts were given a response in this // iteration. Set<String> promptIdsWithResponse = new HashSet<String>(); // Get the indices of each response in the list of responses and then // sort them to ensure that we process each response in the correct // numeric order. List<Integer> indices = new ArrayList<Integer>(responses.keySet()); Collections.sort(indices); // Now, add each of the responses. for(Integer index : indices) { Response response = responses.get(index); // If the response is a prompt response, add its appropriate // columns. if(response instanceof PromptResponse) { numResponses++; if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { String responseId = response.getId(); promptIdsWithResponse.add(responseId); JSONArray values = prompts.get(responseId).getJSONArray(JSON_KEY_VALUES); Object responseValue = response.getResponseValue(); if(OutputFormat.CSV.equals(outputFormat)) { responseValue = "\"" + responseValue + "\""; } values.put(responseValue); } } // FIXME // The problem is that we need to recurse, but if we have already // added all of the survey response stuff then we don't want to // add that again. If I remember correctly, we need to create new // columns with headers that are like, "prompt1name1", // "prompt1name2", etc. where we append the iteration number after // the prompt name. The problem is that before this function is // called we called a generic header creator for each prompt. This // prompt would have had a header that was created but only the // one. We need to duplicate that header, JSONObject.NULL-out all // of the previous responses, and give it a new header with the // iteration number. else if(response instanceof RepeatableSetResponse) { /* RepeatableSetResponse repeatableSetResponse = (RepeatableSetResponse) response; Map<Integer, Map<Integer, Response>> repeatableSetResponses = repeatableSetResponse.getResponseGroups(); List<Integer> rsIterations = new ArrayList<Integer>(repeatableSetResponses.keySet()); for(Integer rsIndex : rsIterations) { numResponses += processResponses(allColumns, surveyResponse, repeatableSetResponses.get(rsIndex), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTime, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } */ } } // Finally, get all of the prompts that didn't receive a value in this // iteration and give them a value of JSONObject.NULL. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { Set<String> promptIdsWithoutResponse = new HashSet<String>(prompts.keySet()); promptIdsWithoutResponse.removeAll(promptIdsWithResponse); for(String currPromptId : promptIdsWithoutResponse) { prompts .get(currPromptId) .getJSONArray(JSON_KEY_VALUES) .put(JSONObject.NULL); } } return numResponses; } }
false
true
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey response read request."); if(isFailed()) { super.respond(httpRequest, httpResponse, null); return; } // Create a writer for the HTTP response object. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse))); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); return; } // Sets the HTTP headers to disable caching. expireResponse(httpResponse); String resultString = ""; if(! isFailed()) { try { boolean allColumns = columns.equals(URN_SPECIAL_ALL_LIST); // TODO: I am fairly confident that these two branches can be // merged further and subsequently cleaned up, but I don't have // the time to tackle it right now. if(OutputFormat.JSON_ROWS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject result = new JSONObject(); result.put(JSON_KEY_RESULT, RESULT_SUCCESS); List<String> uniqueSurveyIds = new LinkedList<String>(); List<String> uniquePromptIds = new LinkedList<String>(); JSONArray results = new JSONArray(); for(SurveyResponse surveyResponse : surveyResponseList) { uniqueSurveyIds.add(surveyResponse.getSurvey().getId()); uniquePromptIds.addAll(surveyResponse.getPromptIds()); JSONObject currResult = surveyResponse.toJson( allColumns || columns.contains(ColumnKey.USER_ID), allColumns || false, allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT), allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE), allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS), allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE), allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS), false, allColumns || columns.contains(ColumnKey.SURVEY_ID), allColumns || columns.contains(ColumnKey.SURVEY_TITLE), allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG), allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE), false, ((returnId == null) ? false : returnId) ); if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { currResult.put( "timestamp", TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { currResult.put( "utc_timestamp", DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { double accuracy = location.getAccuracy(); if(Double.isInfinite(accuracy) || Double.isNaN(accuracy)) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_ACCURACY, accuracy); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { double latitude = location.getLatitude(); if(Double.isInfinite(latitude) || Double.isNaN(latitude)) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LATITUDE, latitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { double longitude = location.getLongitude(); if(Double.isInfinite(longitude) || Double.isNaN(longitude)) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LONGITUDE, longitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_PROVIDER, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_PROVIDER, location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME, location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME_ZONE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME_ZONE, location.getTimeZone().getID()); } } results.put(currResult); } if((collapse != null) && collapse) { int numResults = results.length(); Map<JSONObject, Integer> collapsedMap = new HashMap<JSONObject, Integer>(numResults); for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); Integer prevCount = collapsedMap.put(currResult, 1); if(prevCount != null) { collapsedMap.put(currResult, prevCount + 1); results.remove(i); i--; numResults--; } } for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); currResult.put(JSON_KEY_COUNT, collapsedMap.get(currResult)); } } result.put(JSON_KEY_DATA, results); // Metadata if((suppressMetadata == null) || (! suppressMetadata)) { JSONObject metadata = new JSONObject(); metadata.put(JSON_KEY_NUM_SURVEYS, uniqueSurveyIds.size()); metadata.put(JSON_KEY_NUM_PROMPTS, uniquePromptIds.size()); Collection<String> columnsResult = new HashSet<String>(columns.size()); // If it contains the special 'all' value, add them // all. if(columns.contains(URN_SPECIAL_ALL)) { ColumnKey[] values = SurveyResponse.ColumnKey.values(); for(int i = 0; i < values.length; i++) { columnsResult.add(values[i].toString()); } } // Otherwise, add cycle through them else { for(ColumnKey columnKey : columns) { columnsResult.add(columnKey.toString()); } } // Check if prompt responses were requested, and, if // so, add them to the list of columns. if(columns.contains(SurveyResponse.ColumnKey.PROMPT_RESPONSE) || columns.contains(URN_SPECIAL_ALL)) { for(String promptId : uniquePromptIds) { columnsResult.add(ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } } // Add it to the metadata result. metadata.put(JSON_KEY_ITEMS, columnsResult); result.put(JSON_KEY_METADATA, metadata); } if((prettyPrint != null) && prettyPrint) { resultString = result.toString(4); } else { resultString = result.toString(); } } else if(OutputFormat.JSON_COLUMNS.equals(outputFormat) || OutputFormat.CSV.equals(outputFormat)) { JSONArray usernames = new JSONArray(); JSONArray clients = new JSONArray(); JSONArray privacyStates = new JSONArray(); JSONArray timestamps = new JSONArray(); JSONArray utcTimestamps = new JSONArray(); JSONArray epochMillisTimestamps = new JSONArray(); JSONArray timezones = new JSONArray(); JSONArray locationStatuses = new JSONArray(); JSONArray locationLongitude = new JSONArray(); JSONArray locationLatitude = new JSONArray(); JSONArray locationTimestamp = new JSONArray(); JSONArray locationTimeZone = new JSONArray(); JSONArray locationAccuracy = new JSONArray(); JSONArray locationProvider = new JSONArray(); JSONArray surveyIds = new JSONArray(); JSONArray surveyTitles = new JSONArray(); JSONArray surveyDescriptions = new JSONArray(); JSONArray launchContexts = new JSONArray(); Map<String, JSONObject> prompts = new HashMap<String, JSONObject>(); // If the results are empty, then we still want to populate // the resulting JSON with information about all of the // prompts even though they don't have any responses // associated with them. if(surveyResponseList.isEmpty()) { // If the user-supplied list of survey IDs is present, if(this.surveyIds != null) { Map<String, Survey> campaignSurveys = campaign.getSurveys(); // If the user asked for all surveys for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // all of the surveys in this campaign. if(this.surveyIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaignSurveys.values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information only // with the data about the requested surveys. else { for(String surveyId : this.surveyIds) { populatePrompts(campaignSurveys.get(surveyId).getSurveyItems(), prompts); } } } // If the user-supplied list of prompt IDs is present, else if(promptIds != null) { // If the user asked for all prompts for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // this campaign. if(this.promptIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaign.getSurveys().values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information with // the data about only the requested prompts. else { int currNumPrompts = 0; Map<Integer, SurveyItem> tempPromptMap = new HashMap<Integer, SurveyItem>(promptIds.size()); for(String promptId : promptIds) { tempPromptMap.put(currNumPrompts, campaign.getPrompt(campaign.getSurveyIdForPromptId(promptId), promptId)); currNumPrompts++; } populatePrompts(tempPromptMap, prompts); } } } // If the results are non-empty, we need to populate the // prompt information only for those prompts to which the // user queried about. else { Set<String> unqiueSurveyIds = new HashSet<String>(); Set<String> uniquePromptIds = new HashSet<String>(); // For each of the survey responses in the result, for(SurveyResponse surveyResponse : surveyResponseList) { String surveyId = surveyResponse.getSurvey().getId(); // If the survey with which this survey response is // associated has not yet been processed, process // it. if(! unqiueSurveyIds.contains(surveyId)) { // Add to the list of surveys that have been // processed so that no subsequent survey // responses that are associated with this // survey cause it to be processed again. unqiueSurveyIds.add(surveyId); // Keep track of the unique number of prompts // that we process. int currNumPrompts = 0; // Get all of the unique prompt IDs for this // survey response. Set<String> promptIds = surveyResponse.getPromptIds(); // Create a a temporary map of Integers to // Prompt objects. Map<Integer, SurveyItem> tempPrompts = new HashMap<Integer, SurveyItem>(promptIds.size()); // Retrieve all of the unique prompts that have // not yet been processed and add them to the // map. for(String promptId : promptIds) { if(! uniquePromptIds.contains(promptId)) { tempPrompts.put(currNumPrompts, campaign.getPrompt(surveyId, promptId)); currNumPrompts++; } } // Populate the prompts JSON with the // information about all of the distinct // prompts from this survey response. populatePrompts(tempPrompts, prompts); } } } // Process each of the survey responses and keep track of // the number of prompt responses. int numSurveyResponses = surveyResponseList.size(); int numPromptResponses = 0; for(SurveyResponse surveyResponse : surveyResponseList) { numPromptResponses += processResponses(allColumns, surveyResponse, surveyResponse.getResponses(), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTimestamp, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } // Add all of the applicable output stuff. JSONObject result = new JSONObject(); // For each of the requested columns, add their respective // data to the result. if(allColumns || columns.contains(ColumnKey.USER_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, usernames); result.put(ColumnKey.USER_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, clients); result.put(ColumnKey.CONTEXT_CLIENT.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, privacyStates); result.put(ColumnKey.SURVEY_PRIVACY_STATE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, utcTimestamps); result.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, epochMillisTimestamps); result.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timezones); result.put(ColumnKey.CONTEXT_TIMEZONE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationStatuses); result.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLongitude); result.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLatitude); result.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { JSONObject timeValues = new JSONObject(); timeValues.put(JSON_KEY_VALUES, locationTimestamp); result.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString(), timeValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMEZONE)) { JSONObject timeZoneValues = new JSONObject(); timeZoneValues.put(JSON_KEY_VALUES, locationTimeZone); result.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString(), timeZoneValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationAccuracy); result.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationProvider); result.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyIds); result.put(ColumnKey.SURVEY_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyTitles); result.put(ColumnKey.SURVEY_TITLE.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyDescriptions); result.put(ColumnKey.SURVEY_DESCRIPTION.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString(), values); } if(columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString(), values); } if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { for(String promptId : prompts.keySet()) { result.put( SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId, prompts.get(promptId)); } } // If the user requested to collapse the results, create a // new column called count and set the initial value for // every existing row to 1. Then, create a map of string // representations of data to their original row. Cycle // through the indices creating a string by concatenating // the value at the given index for each column and // checking the map if the string already exists. If it // does not exist, add the string value and have it point // to the current index. If it does exist, go to that // column, increase the count, and delete this row by // deleting whatever is at the current index in every // column. if((collapse != null) && collapse) { // Get the key for each row. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a new "count" column and initialize every // count to 1. JSONArray counts = new JSONArray(); for(int i = 0; i < numSurveyResponses; i++) { counts.put(1); } JSONObject countObject = new JSONObject(); countObject.put(JSON_KEY_VALUES, counts); result.put("urn:ohmage:context:count", countObject); keys.put("urn:ohmage:context:count"); // Cycle through the responses. Map<String, Integer> valueToIndexMap = new HashMap<String, Integer>(); for(int i = 0; i < numSurveyResponses; i++) { // Build the string. StringBuilder currResultBuilder = new StringBuilder(); for(int j = 0; j < keyLength; j++) { currResultBuilder.append(result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).get(i)); if((j + 1) != keyLength) { currResultBuilder.append(','); } } // Check if the string exists. String currResultString = currResultBuilder.toString(); // If so, go to that index in every column // including the count and delete it, effectively // deleting that row. if(valueToIndexMap.containsKey(currResultString)) { int count = result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).getInt(valueToIndexMap.get(currResultString)) + 1; result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).put(valueToIndexMap.get(currResultString).intValue(), count); for(int j = 0; j < keyLength + 1; j++) { result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).remove(i); } i--; numSurveyResponses--; } // If not, add it to the map. else { valueToIndexMap.put(currResultString, i); } } } // If metadata is not suppressed, create it. JSONObject metadata = null; if((suppressMetadata == null) || (! suppressMetadata)) { metadata = new JSONObject(); metadata.put(InputKeys.CAMPAIGN_URN, campaignId); metadata.put(JSON_KEY_NUM_SURVEYS, surveyResponseList.size()); metadata.put(JSON_KEY_NUM_PROMPTS, numPromptResponses); } if(OutputFormat.JSON_COLUMNS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_SUCCESS); if((suppressMetadata == null) || (! suppressMetadata)) { JSONArray itemsJson = new JSONArray(); Iterator<?> keys = result.keys(); while(keys.hasNext()) { itemsJson.put(keys.next()); } metadata.put("items", itemsJson); resultJson.put(JSON_KEY_METADATA, metadata); } resultJson.put(JSON_KEY_DATA, result); if((prettyPrint != null) && prettyPrint) { resultString = resultJson.toString(4); } else { resultString = resultJson.toString(); } } // For CSV output, else if(OutputFormat.CSV.equals(outputFormat)) { // Mark it as an attachment. httpResponse.setContentType("text/csv"); httpResponse.setHeader( "Content-Disposition", "attachment; filename=SurveyResponses.csv"); StringBuilder resultBuilder = new StringBuilder(); // If the metadata is not suppressed, add it to the // output builder. if((suppressMetadata == null) || (! suppressMetadata)) { metadata.put(JSON_KEY_RESULT, RESULT_SUCCESS); resultBuilder.append("## begin metadata\n"); resultBuilder.append('#').append(metadata.toString().replace(',', ';')).append('\n'); resultBuilder.append("## end metadata\n"); } // Add the prompt contexts to the output builder if // prompts were desired. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { resultBuilder.append("## begin prompt contexts\n"); for(String promptId : prompts.keySet()) { JSONObject promptJson = new JSONObject(); // Use the already-generated JSON from each of // the prompts. promptJson.put( promptId, prompts .get(promptId) .get(JSON_KEY_CONTEXT) .toString()); resultBuilder .append('#') .append(promptJson.toString()) .append('\n'); } resultBuilder.append("## end prompt contexts\n"); } // Begin the data section of the CSV. resultBuilder.append("## begin data\n"); // We need to get all of the column header names. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a comma-separated list of the header names. resultBuilder.append('#'); for(int i = 0; i < keyLength; i++) { String header = keys.getString(i); if(header.startsWith("urn:ohmage:")) { header = header.substring(11); if(header.startsWith("prompt:id:")) { header = header.substring(10); } } resultBuilder.append(header); if((i + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); // For each of the responses, for(int i = 0; i < numSurveyResponses; i++) { for(int j = 0; j < keyLength; j++) { Object currResult = result .getJSONObject(keys.getString(j)) .getJSONArray(JSON_KEY_VALUES) .get(i); if(JSONObject.NULL.equals(currResult)) { resultBuilder.append(""); } else { resultBuilder.append(currResult); } if((j + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); } resultBuilder.append("## end data"); resultString = resultBuilder.toString(); } } } catch(JSONException e) { LOGGER.error(e.toString(), e); setFailed(); } } if(isFailed()) { httpResponse.setContentType("text/html"); resultString = this.getFailureMessage(); } try { writer.write(resultString); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); } try { writer.flush(); writer.close(); } catch(IOException e) { LOGGER.error("Unable to flush or close the writer.", e); } }
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey response read request."); if(isFailed()) { super.respond(httpRequest, httpResponse, null); return; } // Create a writer for the HTTP response object. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse))); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); return; } // Sets the HTTP headers to disable caching. expireResponse(httpResponse); String resultString = ""; if(! isFailed()) { try { boolean allColumns = columns.equals(URN_SPECIAL_ALL_LIST); // TODO: I am fairly confident that these two branches can be // merged further and subsequently cleaned up, but I don't have // the time to tackle it right now. if(OutputFormat.JSON_ROWS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject result = new JSONObject(); result.put(JSON_KEY_RESULT, RESULT_SUCCESS); List<String> uniqueSurveyIds = new LinkedList<String>(); List<String> uniquePromptIds = new LinkedList<String>(); JSONArray results = new JSONArray(); for(SurveyResponse surveyResponse : surveyResponseList) { uniqueSurveyIds.add(surveyResponse.getSurvey().getId()); uniquePromptIds.addAll(surveyResponse.getPromptIds()); JSONObject currResult = surveyResponse.toJson( allColumns || columns.contains(ColumnKey.USER_ID), allColumns || false, allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT), allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE), allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS), allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE), allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS), false, allColumns || columns.contains(ColumnKey.SURVEY_ID), allColumns || columns.contains(ColumnKey.SURVEY_TITLE), allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG), allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE), false, ((returnId == null) ? false : returnId) ); if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { currResult.put( "timestamp", TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { currResult.put( "utc_timestamp", DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { double accuracy = location.getAccuracy(); if(Double.isInfinite(accuracy) || Double.isNaN(accuracy)) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_ACCURACY, accuracy); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { double latitude = location.getLatitude(); if(Double.isInfinite(latitude) || Double.isNaN(latitude)) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LATITUDE, latitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { double longitude = location.getLongitude(); if(Double.isInfinite(longitude) || Double.isNaN(longitude)) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LONGITUDE, longitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_PROVIDER, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_PROVIDER, location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME, location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME_ZONE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME_ZONE, location.getTimeZone().getID()); } } results.put(currResult); } if((collapse != null) && collapse) { int numResults = results.length(); Map<JSONObject, Integer> collapsedMap = new HashMap<JSONObject, Integer>(numResults); for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); Integer prevCount = collapsedMap.put(currResult, 1); if(prevCount != null) { collapsedMap.put(currResult, prevCount + 1); results.remove(i); i--; numResults--; } } for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); currResult.put(JSON_KEY_COUNT, collapsedMap.get(currResult)); } } result.put(JSON_KEY_DATA, results); // Metadata if((suppressMetadata == null) || (! suppressMetadata)) { JSONObject metadata = new JSONObject(); metadata.put(JSON_KEY_NUM_SURVEYS, uniqueSurveyIds.size()); metadata.put(JSON_KEY_NUM_PROMPTS, uniquePromptIds.size()); Collection<String> columnsResult = new HashSet<String>(columns.size()); // If it contains the special 'all' value, add them // all. if(columns.contains(URN_SPECIAL_ALL)) { ColumnKey[] values = SurveyResponse.ColumnKey.values(); for(int i = 0; i < values.length; i++) { columnsResult.add(values[i].toString()); } } // Otherwise, add cycle through them else { for(ColumnKey columnKey : columns) { columnsResult.add(columnKey.toString()); } } // Check if prompt responses were requested, and, if // so, add them to the list of columns. if(columns.contains(SurveyResponse.ColumnKey.PROMPT_RESPONSE) || columns.contains(URN_SPECIAL_ALL)) { for(String promptId : uniquePromptIds) { columnsResult.add(ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } } // Add it to the metadata result. metadata.put(JSON_KEY_ITEMS, columnsResult); result.put(JSON_KEY_METADATA, metadata); } if((prettyPrint != null) && prettyPrint) { resultString = result.toString(4); } else { resultString = result.toString(); } } else if(OutputFormat.JSON_COLUMNS.equals(outputFormat) || OutputFormat.CSV.equals(outputFormat)) { JSONArray usernames = new JSONArray(); JSONArray clients = new JSONArray(); JSONArray privacyStates = new JSONArray(); JSONArray timestamps = new JSONArray(); JSONArray utcTimestamps = new JSONArray(); JSONArray epochMillisTimestamps = new JSONArray(); JSONArray timezones = new JSONArray(); JSONArray locationStatuses = new JSONArray(); JSONArray locationLongitude = new JSONArray(); JSONArray locationLatitude = new JSONArray(); JSONArray locationTimestamp = new JSONArray(); JSONArray locationTimeZone = new JSONArray(); JSONArray locationAccuracy = new JSONArray(); JSONArray locationProvider = new JSONArray(); JSONArray surveyIds = new JSONArray(); JSONArray surveyTitles = new JSONArray(); JSONArray surveyDescriptions = new JSONArray(); JSONArray launchContexts = new JSONArray(); Map<String, JSONObject> prompts = new HashMap<String, JSONObject>(); // If the results are empty, then we still want to populate // the resulting JSON with information about all of the // prompts even though they don't have any responses // associated with them. // FIXME: This shouldn't be conditional on the number of // responses found. We should create headers for all of the // requested prompt IDs (either via the list of survey IDs // or the list of prompt IDs) or none of the prompt IDs if // prompts aren't requested. if(surveyResponseList.isEmpty()) { // If the user-supplied list of survey IDs is present, if(this.surveyIds != null) { Map<String, Survey> campaignSurveys = campaign.getSurveys(); // If the user asked for all surveys for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // all of the surveys in this campaign. if(this.surveyIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaignSurveys.values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information only // with the data about the requested surveys. else { for(String surveyId : this.surveyIds) { populatePrompts(campaignSurveys.get(surveyId).getSurveyItems(), prompts); } } } // If the user-supplied list of prompt IDs is present, else if(promptIds != null) { // If the user asked for all prompts for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // this campaign. if(this.promptIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaign.getSurveys().values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information with // the data about only the requested prompts. else { int currNumPrompts = 0; Map<Integer, SurveyItem> tempPromptMap = new HashMap<Integer, SurveyItem>(promptIds.size()); for(String promptId : promptIds) { tempPromptMap.put(currNumPrompts, campaign.getPrompt(campaign.getSurveyIdForPromptId(promptId), promptId)); currNumPrompts++; } populatePrompts(tempPromptMap, prompts); } } } // If the results are non-empty, we need to populate the // prompt information only for those prompts to which the // user queried about. else { Set<String> unqiueSurveyIds = new HashSet<String>(); Set<String> uniquePromptIds = new HashSet<String>(); // For each of the survey responses in the result, for(SurveyResponse surveyResponse : surveyResponseList) { String surveyId = surveyResponse.getSurvey().getId(); // If the survey with which this survey response is // associated has not yet been processed, process // it. if(! unqiueSurveyIds.contains(surveyId)) { // Add to the list of surveys that have been // processed so that no subsequent survey // responses that are associated with this // survey cause it to be processed again. unqiueSurveyIds.add(surveyId); // Keep track of the unique number of prompts // that we process. int currNumPrompts = 0; // Get all of the unique prompt IDs for this // survey response. Set<String> promptIds = surveyResponse.getPromptIds(); // Create a a temporary map of Integers to // Prompt objects. Map<Integer, SurveyItem> tempPrompts = new HashMap<Integer, SurveyItem>(promptIds.size()); // Retrieve all of the unique prompts that have // not yet been processed and add them to the // map. for(String promptId : promptIds) { if(! uniquePromptIds.contains(promptId)) { tempPrompts.put(currNumPrompts, campaign.getPrompt(surveyId, promptId)); currNumPrompts++; } } // Populate the prompts JSON with the // information about all of the distinct // prompts from this survey response. populatePrompts(tempPrompts, prompts); } } } // Process each of the survey responses and keep track of // the number of prompt responses. int numSurveyResponses = surveyResponseList.size(); int numPromptResponses = 0; for(SurveyResponse surveyResponse : surveyResponseList) { numPromptResponses += processResponses(allColumns, surveyResponse, surveyResponse.getResponses(), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTimestamp, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } // Add all of the applicable output stuff. JSONObject result = new JSONObject(); // For each of the requested columns, add their respective // data to the result. if(allColumns || columns.contains(ColumnKey.USER_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, usernames); result.put(ColumnKey.USER_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, clients); result.put(ColumnKey.CONTEXT_CLIENT.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, privacyStates); result.put(ColumnKey.SURVEY_PRIVACY_STATE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, utcTimestamps); result.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, epochMillisTimestamps); result.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timezones); result.put(ColumnKey.CONTEXT_TIMEZONE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationStatuses); result.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLongitude); result.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLatitude); result.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { JSONObject timeValues = new JSONObject(); timeValues.put(JSON_KEY_VALUES, locationTimestamp); result.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString(), timeValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMEZONE)) { JSONObject timeZoneValues = new JSONObject(); timeZoneValues.put(JSON_KEY_VALUES, locationTimeZone); result.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString(), timeZoneValues); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationAccuracy); result.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationProvider); result.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyIds); result.put(ColumnKey.SURVEY_ID.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyTitles); result.put(ColumnKey.SURVEY_TITLE.toString(), values); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyDescriptions); result.put(ColumnKey.SURVEY_DESCRIPTION.toString(), values); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString(), values); } if(columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString(), values); } if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { for(String promptId : prompts.keySet()) { result.put( SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId, prompts.get(promptId)); } } // If the user requested to collapse the results, create a // new column called count and set the initial value for // every existing row to 1. Then, create a map of string // representations of data to their original row. Cycle // through the indices creating a string by concatenating // the value at the given index for each column and // checking the map if the string already exists. If it // does not exist, add the string value and have it point // to the current index. If it does exist, go to that // column, increase the count, and delete this row by // deleting whatever is at the current index in every // column. if((collapse != null) && collapse) { // Get the key for each row. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a new "count" column and initialize every // count to 1. JSONArray counts = new JSONArray(); for(int i = 0; i < numSurveyResponses; i++) { counts.put(1); } JSONObject countObject = new JSONObject(); countObject.put(JSON_KEY_VALUES, counts); result.put("urn:ohmage:context:count", countObject); keys.put("urn:ohmage:context:count"); // Cycle through the responses. Map<String, Integer> valueToIndexMap = new HashMap<String, Integer>(); for(int i = 0; i < numSurveyResponses; i++) { // Build the string. StringBuilder currResultBuilder = new StringBuilder(); for(int j = 0; j < keyLength; j++) { currResultBuilder.append(result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).get(i)); if((j + 1) != keyLength) { currResultBuilder.append(','); } } // Check if the string exists. String currResultString = currResultBuilder.toString(); // If so, go to that index in every column // including the count and delete it, effectively // deleting that row. if(valueToIndexMap.containsKey(currResultString)) { int count = result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).getInt(valueToIndexMap.get(currResultString)) + 1; result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).put(valueToIndexMap.get(currResultString).intValue(), count); for(int j = 0; j < keyLength + 1; j++) { result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).remove(i); } i--; numSurveyResponses--; } // If not, add it to the map. else { valueToIndexMap.put(currResultString, i); } } } // If metadata is not suppressed, create it. JSONObject metadata = null; if((suppressMetadata == null) || (! suppressMetadata)) { metadata = new JSONObject(); metadata.put(InputKeys.CAMPAIGN_URN, campaignId); metadata.put(JSON_KEY_NUM_SURVEYS, surveyResponseList.size()); metadata.put(JSON_KEY_NUM_PROMPTS, numPromptResponses); } if(OutputFormat.JSON_COLUMNS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_SUCCESS); if((suppressMetadata == null) || (! suppressMetadata)) { JSONArray itemsJson = new JSONArray(); Iterator<?> keys = result.keys(); while(keys.hasNext()) { itemsJson.put(keys.next()); } metadata.put("items", itemsJson); resultJson.put(JSON_KEY_METADATA, metadata); } resultJson.put(JSON_KEY_DATA, result); if((prettyPrint != null) && prettyPrint) { resultString = resultJson.toString(4); } else { resultString = resultJson.toString(); } } // For CSV output, else if(OutputFormat.CSV.equals(outputFormat)) { // Mark it as an attachment. httpResponse.setContentType("text/csv"); httpResponse.setHeader( "Content-Disposition", "attachment; filename=SurveyResponses.csv"); StringBuilder resultBuilder = new StringBuilder(); // If the metadata is not suppressed, add it to the // output builder. if((suppressMetadata == null) || (! suppressMetadata)) { metadata.put(JSON_KEY_RESULT, RESULT_SUCCESS); resultBuilder.append("## begin metadata\n"); resultBuilder.append('#').append(metadata.toString().replace(',', ';')).append('\n'); resultBuilder.append("## end metadata\n"); } // Add the prompt contexts to the output builder if // prompts were desired. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { resultBuilder.append("## begin prompt contexts\n"); for(String promptId : prompts.keySet()) { JSONObject promptJson = new JSONObject(); // Use the already-generated JSON from each of // the prompts. promptJson.put( promptId, prompts .get(promptId) .get(JSON_KEY_CONTEXT)); resultBuilder .append('#') .append(promptJson.toString()) .append('\n'); } resultBuilder.append("## end prompt contexts\n"); } // Begin the data section of the CSV. resultBuilder.append("## begin data\n"); // We need to get all of the column header names. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a comma-separated list of the header names. resultBuilder.append('#'); for(int i = 0; i < keyLength; i++) { String header = keys.getString(i); if(header.startsWith("urn:ohmage:")) { header = header.substring(11); if(header.startsWith("prompt:id:")) { header = header.substring(10); } } resultBuilder.append(header); if((i + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); // For each of the responses, for(int i = 0; i < numSurveyResponses; i++) { for(int j = 0; j < keyLength; j++) { Object currResult = result .getJSONObject(keys.getString(j)) .getJSONArray(JSON_KEY_VALUES) .get(i); if(JSONObject.NULL.equals(currResult)) { resultBuilder.append(""); } else { resultBuilder.append(currResult); } if((j + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); } resultBuilder.append("## end data"); resultString = resultBuilder.toString(); } } } catch(JSONException e) { LOGGER.error(e.toString(), e); setFailed(); } } if(isFailed()) { httpResponse.setContentType("text/html"); resultString = this.getFailureMessage(); } try { writer.write(resultString); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); } try { writer.flush(); writer.close(); } catch(IOException e) { LOGGER.error("Unable to flush or close the writer.", e); } }
diff --git a/WEB-INF/src/edu/wustl/catissuecore/action/SimpleSearchAction.java b/WEB-INF/src/edu/wustl/catissuecore/action/SimpleSearchAction.java index 677d204cd..48c580b11 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/action/SimpleSearchAction.java +++ b/WEB-INF/src/edu/wustl/catissuecore/action/SimpleSearchAction.java @@ -1,207 +1,210 @@ /** * Created on Aug 17, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package edu.wustl.catissuecore.action; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import edu.wustl.catissuecore.actionForm.SimpleQueryInterfaceForm; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.DistributionProtocol; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.query.Query; import edu.wustl.catissuecore.query.QueryFactory; import edu.wustl.catissuecore.query.SimpleConditionsNode; import edu.wustl.catissuecore.query.SimpleQuery; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.util.MapDataParser; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; /** * @author gautam_shetty */ public class SimpleSearchAction extends DispatchAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form; //Get the aliasName. String viewAliasName = (String)simpleQueryInterfaceForm .getValue("SimpleConditionsNode:1_Condition_DataElement_table"); String target = Constants.SUCCESS; try { Map map = simpleQueryInterfaceForm.getValuesMap(); MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.query"); Collection simpleConditionNodeCollection = parser.generateData(map, true); Iterator iterator = simpleConditionNodeCollection.iterator(); Set fromTables = new HashSet(); SimpleConditionsNode simpleConditionsNode = null; while (iterator.hasNext()) { simpleConditionsNode = (SimpleConditionsNode)iterator.next(); String columnName = simpleConditionsNode.getCondition().getDataElement().getField(); StringTokenizer stringToken = new StringTokenizer(columnName,"."); simpleConditionsNode.getCondition().getDataElement().setTable(stringToken.nextToken()); simpleConditionsNode.getCondition().getDataElement().setField(stringToken.nextToken()); String fieldType = stringToken.nextToken(); String value = simpleConditionsNode.getCondition().getValue(); if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR) || fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_DATE)) { if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR)) { value = "'"+value+"'"; } else { value = "STR_TO_DATE('"+value+"','"+Constants.MYSQL_DATE_PATTERN+"')"; } simpleConditionsNode.getCondition().setValue(value); } if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { //Prepare a Set of table names. fromTables.add(simpleConditionsNode.getCondition().getDataElement().getTable()); } } if(hasActivityStatus(viewAliasName)) { Logger.out.debug("Adding ActivityStatus............................"); SimpleConditionsNode activityStatusCondition = new SimpleConditionsNode(); - activityStatusCondition.getCondition().getDataElement().setTable(viewAliasName); + if(viewAliasName.indexOf("CollectionProtocol")!=-1 || viewAliasName.indexOf("DistributionProtocol")!=-1) + activityStatusCondition.getCondition().getDataElement().setTable("SpecimenProtocol"); + else + activityStatusCondition.getCondition().getDataElement().setTable(viewAliasName); activityStatusCondition.getCondition().getDataElement().setField("ACTIVITY_STATUS"); activityStatusCondition.getCondition().getOperator().setOperator("!="); activityStatusCondition.getCondition().setValue("'"+Constants.ACTIVITY_STATUS_DISABLED+"'"); simpleConditionsNode.getOperator().setOperator(Constants.AND_JOIN_CONDITION); simpleConditionNodeCollection.add(activityStatusCondition); } // Iterator iterator1 = fromTables.iterator(); // while (iterator1.hasNext()) // { // Logger.out.debug("From tABLES............................."+iterator1.next()); // } Query query = QueryFactory.getInstance().newQuery(Query.SIMPLE_QUERY, viewAliasName); //Get the view columns. String [] columnNames = query.setViewElements(viewAliasName); if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { query.setTableSet(fromTables); Logger.out.debug("setTableSet......................................."); } ((SimpleQuery)query).addConditions(simpleConditionNodeCollection); List list = query.execute(); if (list.isEmpty()) { ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("simpleQuery.noRecordsFound")); saveErrors(request,errors); String path = "SimpleQueryInterface.do?pageOf="+simpleQueryInterfaceForm.getPageOf()+"&aliasName="+simpleQueryInterfaceForm.getAliasName(); RequestDispatcher requestDispatcher = request.getRequestDispatcher(path); requestDispatcher.forward(request,response); } else { if (list.size() == 1) { List rowList = (List)list.get(0); String action = "SearchObject.do?pageOf="+simpleQueryInterfaceForm.getPageOf() + "&operation=search&systemIdentifier=" + rowList.get(0); RequestDispatcher requestDispatcher = request.getRequestDispatcher(action); requestDispatcher.forward(request,response); } else { request.setAttribute(Constants.PAGEOF, simpleQueryInterfaceForm.getPageOf()); request.setAttribute(Constants.SPREADSHEET_DATA_LIST, list); request.setAttribute(Constants.SPREADSHEET_COLUMN_LIST, columnNames); } } } catch(DAOException daoExp) { Logger.out.debug(daoExp.getMessage(), daoExp); target = Constants.FAILURE; } return mapping.findForward(target); } /** * Returns true if the object named aliasName contains the activityStatus * data member, else returns false. * @param aliasName * @return */ //TODO To be fix private boolean hasActivityStatus(String aliasName) { try { Class className = Class.forName("edu.wustl.catissuecore.domain."+aliasName); if(className.equals(CollectionProtocol.class) || className.equals(DistributionProtocol.class) || className.equals(Specimen.class)) return true; Logger.out.debug("Class.................."+className.getName()); Field[] objectFields = className.getDeclaredFields(); Logger.out.debug("Field Size..........................."+objectFields.length); for (int i=0;i<objectFields.length;i++) { Logger.out.debug("objectFields[i].getName().............................."+objectFields[i].getName()); if (objectFields[i].getName().equals(Constants.ACTIVITY_STATUS)) { return true; } } } catch(ClassNotFoundException classNotExcp) { Logger.out.debug(classNotExcp.getMessage(),classNotExcp); } return false; } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form; //Get the aliasName. String viewAliasName = (String)simpleQueryInterfaceForm .getValue("SimpleConditionsNode:1_Condition_DataElement_table"); String target = Constants.SUCCESS; try { Map map = simpleQueryInterfaceForm.getValuesMap(); MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.query"); Collection simpleConditionNodeCollection = parser.generateData(map, true); Iterator iterator = simpleConditionNodeCollection.iterator(); Set fromTables = new HashSet(); SimpleConditionsNode simpleConditionsNode = null; while (iterator.hasNext()) { simpleConditionsNode = (SimpleConditionsNode)iterator.next(); String columnName = simpleConditionsNode.getCondition().getDataElement().getField(); StringTokenizer stringToken = new StringTokenizer(columnName,"."); simpleConditionsNode.getCondition().getDataElement().setTable(stringToken.nextToken()); simpleConditionsNode.getCondition().getDataElement().setField(stringToken.nextToken()); String fieldType = stringToken.nextToken(); String value = simpleConditionsNode.getCondition().getValue(); if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR) || fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_DATE)) { if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR)) { value = "'"+value+"'"; } else { value = "STR_TO_DATE('"+value+"','"+Constants.MYSQL_DATE_PATTERN+"')"; } simpleConditionsNode.getCondition().setValue(value); } if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { //Prepare a Set of table names. fromTables.add(simpleConditionsNode.getCondition().getDataElement().getTable()); } } if(hasActivityStatus(viewAliasName)) { Logger.out.debug("Adding ActivityStatus............................"); SimpleConditionsNode activityStatusCondition = new SimpleConditionsNode(); activityStatusCondition.getCondition().getDataElement().setTable(viewAliasName); activityStatusCondition.getCondition().getDataElement().setField("ACTIVITY_STATUS"); activityStatusCondition.getCondition().getOperator().setOperator("!="); activityStatusCondition.getCondition().setValue("'"+Constants.ACTIVITY_STATUS_DISABLED+"'"); simpleConditionsNode.getOperator().setOperator(Constants.AND_JOIN_CONDITION); simpleConditionNodeCollection.add(activityStatusCondition); } // Iterator iterator1 = fromTables.iterator(); // while (iterator1.hasNext()) // { // Logger.out.debug("From tABLES............................."+iterator1.next()); // } Query query = QueryFactory.getInstance().newQuery(Query.SIMPLE_QUERY, viewAliasName); //Get the view columns. String [] columnNames = query.setViewElements(viewAliasName); if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { query.setTableSet(fromTables); Logger.out.debug("setTableSet......................................."); } ((SimpleQuery)query).addConditions(simpleConditionNodeCollection); List list = query.execute(); if (list.isEmpty()) { ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("simpleQuery.noRecordsFound")); saveErrors(request,errors); String path = "SimpleQueryInterface.do?pageOf="+simpleQueryInterfaceForm.getPageOf()+"&aliasName="+simpleQueryInterfaceForm.getAliasName(); RequestDispatcher requestDispatcher = request.getRequestDispatcher(path); requestDispatcher.forward(request,response); } else { if (list.size() == 1) { List rowList = (List)list.get(0); String action = "SearchObject.do?pageOf="+simpleQueryInterfaceForm.getPageOf() + "&operation=search&systemIdentifier=" + rowList.get(0); RequestDispatcher requestDispatcher = request.getRequestDispatcher(action); requestDispatcher.forward(request,response); } else { request.setAttribute(Constants.PAGEOF, simpleQueryInterfaceForm.getPageOf()); request.setAttribute(Constants.SPREADSHEET_DATA_LIST, list); request.setAttribute(Constants.SPREADSHEET_COLUMN_LIST, columnNames); } } } catch(DAOException daoExp) { Logger.out.debug(daoExp.getMessage(), daoExp); target = Constants.FAILURE; } return mapping.findForward(target); }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form; //Get the aliasName. String viewAliasName = (String)simpleQueryInterfaceForm .getValue("SimpleConditionsNode:1_Condition_DataElement_table"); String target = Constants.SUCCESS; try { Map map = simpleQueryInterfaceForm.getValuesMap(); MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.query"); Collection simpleConditionNodeCollection = parser.generateData(map, true); Iterator iterator = simpleConditionNodeCollection.iterator(); Set fromTables = new HashSet(); SimpleConditionsNode simpleConditionsNode = null; while (iterator.hasNext()) { simpleConditionsNode = (SimpleConditionsNode)iterator.next(); String columnName = simpleConditionsNode.getCondition().getDataElement().getField(); StringTokenizer stringToken = new StringTokenizer(columnName,"."); simpleConditionsNode.getCondition().getDataElement().setTable(stringToken.nextToken()); simpleConditionsNode.getCondition().getDataElement().setField(stringToken.nextToken()); String fieldType = stringToken.nextToken(); String value = simpleConditionsNode.getCondition().getValue(); if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR) || fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_DATE)) { if (fieldType.equalsIgnoreCase(Constants.FIELD_TYPE_VARCHAR)) { value = "'"+value+"'"; } else { value = "STR_TO_DATE('"+value+"','"+Constants.MYSQL_DATE_PATTERN+"')"; } simpleConditionsNode.getCondition().setValue(value); } if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { //Prepare a Set of table names. fromTables.add(simpleConditionsNode.getCondition().getDataElement().getTable()); } } if(hasActivityStatus(viewAliasName)) { Logger.out.debug("Adding ActivityStatus............................"); SimpleConditionsNode activityStatusCondition = new SimpleConditionsNode(); if(viewAliasName.indexOf("CollectionProtocol")!=-1 || viewAliasName.indexOf("DistributionProtocol")!=-1) activityStatusCondition.getCondition().getDataElement().setTable("SpecimenProtocol"); else activityStatusCondition.getCondition().getDataElement().setTable(viewAliasName); activityStatusCondition.getCondition().getDataElement().setField("ACTIVITY_STATUS"); activityStatusCondition.getCondition().getOperator().setOperator("!="); activityStatusCondition.getCondition().setValue("'"+Constants.ACTIVITY_STATUS_DISABLED+"'"); simpleConditionsNode.getOperator().setOperator(Constants.AND_JOIN_CONDITION); simpleConditionNodeCollection.add(activityStatusCondition); } // Iterator iterator1 = fromTables.iterator(); // while (iterator1.hasNext()) // { // Logger.out.debug("From tABLES............................."+iterator1.next()); // } Query query = QueryFactory.getInstance().newQuery(Query.SIMPLE_QUERY, viewAliasName); //Get the view columns. String [] columnNames = query.setViewElements(viewAliasName); if (simpleQueryInterfaceForm.getPageOf().equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE)) { query.setTableSet(fromTables); Logger.out.debug("setTableSet......................................."); } ((SimpleQuery)query).addConditions(simpleConditionNodeCollection); List list = query.execute(); if (list.isEmpty()) { ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("simpleQuery.noRecordsFound")); saveErrors(request,errors); String path = "SimpleQueryInterface.do?pageOf="+simpleQueryInterfaceForm.getPageOf()+"&aliasName="+simpleQueryInterfaceForm.getAliasName(); RequestDispatcher requestDispatcher = request.getRequestDispatcher(path); requestDispatcher.forward(request,response); } else { if (list.size() == 1) { List rowList = (List)list.get(0); String action = "SearchObject.do?pageOf="+simpleQueryInterfaceForm.getPageOf() + "&operation=search&systemIdentifier=" + rowList.get(0); RequestDispatcher requestDispatcher = request.getRequestDispatcher(action); requestDispatcher.forward(request,response); } else { request.setAttribute(Constants.PAGEOF, simpleQueryInterfaceForm.getPageOf()); request.setAttribute(Constants.SPREADSHEET_DATA_LIST, list); request.setAttribute(Constants.SPREADSHEET_COLUMN_LIST, columnNames); } } } catch(DAOException daoExp) { Logger.out.debug(daoExp.getMessage(), daoExp); target = Constants.FAILURE; } return mapping.findForward(target); }
diff --git a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java index 784aece60..f1a287da3 100644 --- a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java +++ b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java @@ -1,50 +1,50 @@ /* * Sonar Java * Copyright (C) 2012 SonarSource * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.java.api; import org.sonar.api.BatchExtension; import org.sonar.api.ServerExtension; import org.sonar.api.config.Settings; /** * @since 1.1 */ public class JavaSettings implements BatchExtension, ServerExtension { private static final String PROPERTY_COVERAGE_PLUGIN = "sonar.java.coveragePlugin"; private Settings settings; public JavaSettings(Settings settings) { this.settings = settings; } /** * @since 1.1 */ public String getEnabledCoveragePlugin() { - // backward-compatibility with the property '' that has been deprecated in sonar 3.4. + // backward-compatibility with the property that has been deprecated in sonar 3.4. String[] keys = settings.getStringArray("sonar.core.codeCoveragePlugin"); if (keys.length>0) { return keys[0]; } return settings.getString(PROPERTY_COVERAGE_PLUGIN); } }
true
true
public String getEnabledCoveragePlugin() { // backward-compatibility with the property '' that has been deprecated in sonar 3.4. String[] keys = settings.getStringArray("sonar.core.codeCoveragePlugin"); if (keys.length>0) { return keys[0]; } return settings.getString(PROPERTY_COVERAGE_PLUGIN); }
public String getEnabledCoveragePlugin() { // backward-compatibility with the property that has been deprecated in sonar 3.4. String[] keys = settings.getStringArray("sonar.core.codeCoveragePlugin"); if (keys.length>0) { return keys[0]; } return settings.getString(PROPERTY_COVERAGE_PLUGIN); }
diff --git a/servers/src/org/xtreemfs/new_mrc/dbaccess/AtomicBabuDBUpdate.java b/servers/src/org/xtreemfs/new_mrc/dbaccess/AtomicBabuDBUpdate.java index 91b4492f..492601f4 100644 --- a/servers/src/org/xtreemfs/new_mrc/dbaccess/AtomicBabuDBUpdate.java +++ b/servers/src/org/xtreemfs/new_mrc/dbaccess/AtomicBabuDBUpdate.java @@ -1,73 +1,73 @@ /* Copyright (c) 2008 Konrad-Zuse-Zentrum fuer Informationstechnik Berlin. This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based Grid Operating System, see <http://www.xtreemos.eu> for more details. The XtreemOS project has been developed with the financial support of the European Commission's IST program under contract #FP6-033576. XtreemFS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. XtreemFS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XtreemFS. If not, see <http://www.gnu.org/licenses/>. */ /* * AUTHORS: Jan Stender (ZIB) */ package org.xtreemfs.new_mrc.dbaccess; import org.xtreemfs.babudb.BabuDB; import org.xtreemfs.babudb.BabuDBException; import org.xtreemfs.babudb.BabuDBInsertGroup; import org.xtreemfs.babudb.BabuDBRequestListener; public class AtomicBabuDBUpdate implements AtomicDBUpdate { private BabuDBInsertGroup ig; private BabuDB database; private BabuDBRequestListener listener; private Object context; public AtomicBabuDBUpdate(BabuDB database, String dbName, BabuDBRequestListener listener, Object context) throws BabuDBException { ig = database.createInsertGroup(dbName); this.database = database; this.listener = listener; this.context = context; } @Override public void addUpdate(Object... update) { ig.addInsert((Integer) update[0], (byte[]) update[1], (byte[]) update[2]); } @Override public void execute() throws DatabaseException { try { if (listener != null) { - database.syncInsert(ig); + database.directInsert(ig); listener.insertFinished(context); } else - database.syncInsert(ig); + database.directInsert(ig); } catch (BabuDBException exc) { throw new DatabaseException(exc); } } public String toString() { return ig.toString(); } }
false
true
public void execute() throws DatabaseException { try { if (listener != null) { database.syncInsert(ig); listener.insertFinished(context); } else database.syncInsert(ig); } catch (BabuDBException exc) { throw new DatabaseException(exc); } }
public void execute() throws DatabaseException { try { if (listener != null) { database.directInsert(ig); listener.insertFinished(context); } else database.directInsert(ig); } catch (BabuDBException exc) { throw new DatabaseException(exc); } }
diff --git a/src/java/org/apache/commons/math/ode/events/EventState.java b/src/java/org/apache/commons/math/ode/events/EventState.java index 412d85e36..a8641a35f 100644 --- a/src/java/org/apache/commons/math/ode/events/EventState.java +++ b/src/java/org/apache/commons/math/ode/events/EventState.java @@ -1,329 +1,337 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.ode.events; import java.io.Serializable; import org.apache.commons.math.ConvergenceException; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.solvers.BrentSolver; import org.apache.commons.math.ode.DerivativeException; import org.apache.commons.math.ode.sampling.StepInterpolator; /** This class handles the state for one {@link EventHandler * event handler} during integration steps. * * <p>Each time the integrator proposes a step, the event handler * switching function should be checked. This class handles the state * of one handler during one integration step, with references to the * state at the end of the preceding step. This information is used to * decide if the handler should trigger an event or not during the * proposed step (and hence the step should be reduced to ensure the * event occurs at a bound rather than inside the step).</p> * * @version $Revision$ $Date$ * @since 1.2 */ public class EventState implements Serializable { /** Serializable version identifier. */ private static final long serialVersionUID = -216176055159247559L; /** Event handler. */ private final EventHandler handler; /** Maximal time interval between events handler checks. */ private final double maxCheckInterval; /** Convergence threshold for event localization. */ private final double convergence; /** Upper limit in the iteration count for event localization. */ private final int maxIterationCount; /** Time at the beginning of the step. */ private double t0; /** Value of the events handler at the beginning of the step. */ private double g0; /** Simulated sign of g0 (we cheat when crossing events). */ private boolean g0Positive; /** Indicator of event expected during the step. */ private boolean pendingEvent; /** Occurrence time of the pending event. */ private double pendingEventTime; /** Occurrence time of the previous event. */ private double previousEventTime; /** Integration direction. */ private boolean forward; /** Variation direction around pending event. * (this is considered with respect to the integration direction) */ private boolean increasing; /** Next action indicator. */ private int nextAction; /** Simple constructor. * @param handler event handler * @param maxCheckInterval maximal time interval between switching * function checks (this interval prevents missing sign changes in * case the integration steps becomes very large) * @param convergence convergence threshold in the event time search * @param maxIterationCount upper limit of the iteration count in * the event time search */ public EventState(final EventHandler handler, final double maxCheckInterval, final double convergence, final int maxIterationCount) { this.handler = handler; this.maxCheckInterval = maxCheckInterval; this.convergence = Math.abs(convergence); this.maxIterationCount = maxIterationCount; // some dummy values ... t0 = Double.NaN; g0 = Double.NaN; g0Positive = true; pendingEvent = false; pendingEventTime = Double.NaN; previousEventTime = Double.NaN; increasing = true; nextAction = EventHandler.CONTINUE; } /** Get the underlying event handler. * @return underlying event handler */ public EventHandler getEventHandler() { return handler; } /** Get the maximal time interval between events handler checks. * @return maximal time interval between events handler checks */ public double getMaxCheckInterval() { return maxCheckInterval; } /** Get the convergence threshold for event localization. * @return convergence threshold for event localization */ public double getConvergence() { return convergence; } /** Get the upper limit in the iteration count for event localization. * @return upper limit in the iteration count for event localization */ public int getMaxIterationCount() { return maxIterationCount; } /** Reinitialize the beginning of the step. * @param t0 value of the independent <i>time</i> variable at the * beginning of the step * @param y0 array containing the current value of the state vector * at the beginning of the step * @exception EventException if the event handler * value cannot be evaluated at the beginning of the step */ public void reinitializeBegin(final double t0, final double[] y0) throws EventException { this.t0 = t0; g0 = handler.g(t0, y0); g0Positive = (g0 >= 0); } /** Evaluate the impact of the proposed step on the event handler. * @param interpolator step interpolator for the proposed step * @return true if the event handler triggers an event before * the end of the proposed step (this implies the step should be * rejected) * @exception DerivativeException if the interpolator fails to * compute the switching function somewhere within the step * @exception EventException if the switching function * cannot be evaluated * @exception ConvergenceException if an event cannot be located */ public boolean evaluateStep(final StepInterpolator interpolator) throws DerivativeException, EventException, ConvergenceException { try { forward = interpolator.isForward(); final double t1 = interpolator.getCurrentTime(); final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval)); final double h = (t1 - t0) / n; double ta = t0; double ga = g0; double tb = t0 + (interpolator.isForward() ? convergence : -convergence); for (int i = 0; i < n; ++i) { // evaluate handler value at the end of the substep tb += h; interpolator.setInterpolatedTime(tb); final double gb = handler.g(tb, interpolator.getInterpolatedState()); // check events occurrence if (g0Positive ^ (gb >= 0)) { // there is a sign change: an event is expected during this step // variation direction, with respect to the integration direction increasing = (gb >= ga); final UnivariateRealFunction f = new UnivariateRealFunction() { private static final long serialVersionUID = 620905575148456915L; public double value(final double t) throws FunctionEvaluationException { try { interpolator.setInterpolatedTime(t); return handler.g(t, interpolator.getInterpolatedState()); } catch (DerivativeException e) { throw new FunctionEvaluationException(e, t); } catch (EventException e) { throw new FunctionEvaluationException(e, t); } } }; final BrentSolver solver = new BrentSolver(); solver.setAbsoluteAccuracy(convergence); solver.setMaximalIterationCount(maxIterationCount); - final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); - if (Math.abs(root - ta) <= convergence) { - // we have found (again ?) a past event, we simply ignore it + double root; + try { + root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); + } catch (IllegalArgumentException iae) { + // the interval did not really bracket a root + root = Double.NaN; + } + if (Double.isNaN(root) || + ((Math.abs(root - ta) <= convergence) && + (Math.abs(root - previousEventTime) <= convergence))) { + // we have either found nothing or found (again ?) a past event, we simply ignore it ta = tb; ga = gb; } else if (Double.isNaN(previousEventTime) || - (Math.abs(previousEventTime - root) > convergence)) { + (Math.abs(previousEventTime - root) > convergence)) { pendingEventTime = root; if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) { // we were already waiting for this event which was // found during a previous call for a step that was // rejected, this step must now be accepted since it // properly ends exactly at the event occurrence return false; } // either we were not waiting for the event or it has // moved in such a way the step cannot be accepted pendingEvent = true; return true; } } else { // no sign change: there is no event for now ta = tb; ga = gb; } } // no event during the whole step pendingEvent = false; pendingEventTime = Double.NaN; return false; } catch (FunctionEvaluationException e) { final Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof DerivativeException)) { throw (DerivativeException) cause; } else if ((cause != null) && (cause instanceof EventException)) { throw (EventException) cause; } throw new EventException(e); } } /** Get the occurrence time of the event triggered in the current * step. * @return occurrence time of the event triggered in the current * step. */ public double getEventTime() { return pendingEventTime; } /** Acknowledge the fact the step has been accepted by the integrator. * @param t value of the independent <i>time</i> variable at the * end of the step * @param y array containing the current value of the state vector * at the end of the step * @exception EventException if the value of the event * handler cannot be evaluated */ public void stepAccepted(final double t, final double[] y) throws EventException { t0 = t; g0 = handler.g(t, y); if (pendingEvent) { // force the sign to its value "just after the event" previousEventTime = t; g0Positive = increasing; nextAction = handler.eventOccurred(t, y, !(increasing ^ forward)); } else { g0Positive = (g0 >= 0); nextAction = EventHandler.CONTINUE; } } /** Check if the integration should be stopped at the end of the * current step. * @return true if the integration should be stopped */ public boolean stop() { return nextAction == EventHandler.STOP; } /** Let the event handler reset the state if it wants. * @param t value of the independent <i>time</i> variable at the * beginning of the next step * @param y array were to put the desired state vector at the beginning * of the next step * @return true if the integrator should reset the derivatives too * @exception EventException if the state cannot be reseted by the event * handler */ public boolean reset(final double t, final double[] y) throws EventException { if (! pendingEvent) { return false; } if (nextAction == EventHandler.RESET_STATE) { handler.resetState(t, y); } pendingEvent = false; pendingEventTime = Double.NaN; return (nextAction == EventHandler.RESET_STATE) || (nextAction == EventHandler.RESET_DERIVATIVES); } }
false
true
public boolean evaluateStep(final StepInterpolator interpolator) throws DerivativeException, EventException, ConvergenceException { try { forward = interpolator.isForward(); final double t1 = interpolator.getCurrentTime(); final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval)); final double h = (t1 - t0) / n; double ta = t0; double ga = g0; double tb = t0 + (interpolator.isForward() ? convergence : -convergence); for (int i = 0; i < n; ++i) { // evaluate handler value at the end of the substep tb += h; interpolator.setInterpolatedTime(tb); final double gb = handler.g(tb, interpolator.getInterpolatedState()); // check events occurrence if (g0Positive ^ (gb >= 0)) { // there is a sign change: an event is expected during this step // variation direction, with respect to the integration direction increasing = (gb >= ga); final UnivariateRealFunction f = new UnivariateRealFunction() { private static final long serialVersionUID = 620905575148456915L; public double value(final double t) throws FunctionEvaluationException { try { interpolator.setInterpolatedTime(t); return handler.g(t, interpolator.getInterpolatedState()); } catch (DerivativeException e) { throw new FunctionEvaluationException(e, t); } catch (EventException e) { throw new FunctionEvaluationException(e, t); } } }; final BrentSolver solver = new BrentSolver(); solver.setAbsoluteAccuracy(convergence); solver.setMaximalIterationCount(maxIterationCount); final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); if (Math.abs(root - ta) <= convergence) { // we have found (again ?) a past event, we simply ignore it ta = tb; ga = gb; } else if (Double.isNaN(previousEventTime) || (Math.abs(previousEventTime - root) > convergence)) { pendingEventTime = root; if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) { // we were already waiting for this event which was // found during a previous call for a step that was // rejected, this step must now be accepted since it // properly ends exactly at the event occurrence return false; } // either we were not waiting for the event or it has // moved in such a way the step cannot be accepted pendingEvent = true; return true; } } else { // no sign change: there is no event for now ta = tb; ga = gb; } } // no event during the whole step pendingEvent = false; pendingEventTime = Double.NaN; return false; } catch (FunctionEvaluationException e) { final Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof DerivativeException)) { throw (DerivativeException) cause; } else if ((cause != null) && (cause instanceof EventException)) { throw (EventException) cause; } throw new EventException(e); } }
public boolean evaluateStep(final StepInterpolator interpolator) throws DerivativeException, EventException, ConvergenceException { try { forward = interpolator.isForward(); final double t1 = interpolator.getCurrentTime(); final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval)); final double h = (t1 - t0) / n; double ta = t0; double ga = g0; double tb = t0 + (interpolator.isForward() ? convergence : -convergence); for (int i = 0; i < n; ++i) { // evaluate handler value at the end of the substep tb += h; interpolator.setInterpolatedTime(tb); final double gb = handler.g(tb, interpolator.getInterpolatedState()); // check events occurrence if (g0Positive ^ (gb >= 0)) { // there is a sign change: an event is expected during this step // variation direction, with respect to the integration direction increasing = (gb >= ga); final UnivariateRealFunction f = new UnivariateRealFunction() { private static final long serialVersionUID = 620905575148456915L; public double value(final double t) throws FunctionEvaluationException { try { interpolator.setInterpolatedTime(t); return handler.g(t, interpolator.getInterpolatedState()); } catch (DerivativeException e) { throw new FunctionEvaluationException(e, t); } catch (EventException e) { throw new FunctionEvaluationException(e, t); } } }; final BrentSolver solver = new BrentSolver(); solver.setAbsoluteAccuracy(convergence); solver.setMaximalIterationCount(maxIterationCount); double root; try { root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); } catch (IllegalArgumentException iae) { // the interval did not really bracket a root root = Double.NaN; } if (Double.isNaN(root) || ((Math.abs(root - ta) <= convergence) && (Math.abs(root - previousEventTime) <= convergence))) { // we have either found nothing or found (again ?) a past event, we simply ignore it ta = tb; ga = gb; } else if (Double.isNaN(previousEventTime) || (Math.abs(previousEventTime - root) > convergence)) { pendingEventTime = root; if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) { // we were already waiting for this event which was // found during a previous call for a step that was // rejected, this step must now be accepted since it // properly ends exactly at the event occurrence return false; } // either we were not waiting for the event or it has // moved in such a way the step cannot be accepted pendingEvent = true; return true; } } else { // no sign change: there is no event for now ta = tb; ga = gb; } } // no event during the whole step pendingEvent = false; pendingEventTime = Double.NaN; return false; } catch (FunctionEvaluationException e) { final Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof DerivativeException)) { throw (DerivativeException) cause; } else if ((cause != null) && (cause instanceof EventException)) { throw (EventException) cause; } throw new EventException(e); } }
diff --git a/java/target/src/common/com/jopdesign/sys/GC.java b/java/target/src/common/com/jopdesign/sys/GC.java index cfb79bef..05b83042 100644 --- a/java/target/src/common/com/jopdesign/sys/GC.java +++ b/java/target/src/common/com/jopdesign/sys/GC.java @@ -1,865 +1,865 @@ /* This file is part of JOP, the Java Optimized Processor see <http://www.jopdesign.com/> Copyright (C) 2005-2008, Martin Schoeberl ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jopdesign.sys; /** * Real-time garbage collection for JOP * * @author Martin Schoeberl ([email protected]) * */ public class GC { /** * Use either scoped memories or a GC. * Combining scopes and the GC needs some extra work. */ final static boolean USE_SCOPES = false; static int mem_start; // read from memory // get a effective heap size with fixed handle count // for our RT-GC tests static int full_heap_size; /** * Fields in the handle structure. * * WARNING: Don't change the size as long * as we do conservative stack scanning. */ static final int HANDLE_SIZE = 8; /** * The handle contains following data: * 0 pointer to the object in the heap or 0 when the handle is free * 1 pointer to the method table or length of an array * 2 size - could be in class info * 3 type info: object, primitve array or ref array * 4 pointer to next handle of same type (used or free) * 5 gray list * 6 space marker - either toSpace or fromSpace * * !!! be carefule when changing the handle structure, it's * used in System.arraycopy() and probably in jvm.asm!!! */ public static final int OFF_PTR = 0; public static final int OFF_MTAB_ALEN = 1; public static final int OFF_SIZE = 2; public static final int OFF_TYPE = 3; // size != array length (think about long/double) // use array types 4..11 are standard boolean to long // our addition: // 1 reference // 0 a plain object public static final int IS_OBJ = 0; public static final int IS_REFARR = 1; /** * Free and Use list. */ static final int OFF_NEXT = 4; /** * Threading the gray list. End of list is 'special' value -1. * 0 means not in list. */ static final int OFF_GREY = 5; /** * Special end of list marker -1 */ static final int GREY_END = -1; /** * Denote in which space the object is */ static final int OFF_SPACE = 6; static final int TYPICAL_OBJ_SIZE = 5; static int handle_cnt; /** * Size of one semi-space, complete heap is two times * the semi_size */ static int semi_size; static int heapStartA, heapStartB; static boolean useA; static int fromSpace; static int toSpace; /** * Points to the start of the to-space after * a flip. Objects are copied to copyPtr and * copyPtr is incremented. */ static int copyPtr; /** * Points to the end of the to-space after * a flip. Objects are allocated from the end * and allocPtr gets decremented. */ static int allocPtr; static int freeList; // TODO: useList is only used for a faster handle sweep // do we need it? static int useList; static int greyList; static int addrStaticRefs; static Object mutex; static boolean concurrentGc; static int roots[]; static void init(int mem_size, int addr) { addrStaticRefs = addr; mem_start = Native.rdMem(0); // align mem_start to 8 word boundary for the // conservative handle check //mem_start = 261300; mem_start = (mem_start+7)&0xfffffff8; //mem_size = mem_start + 2000; full_heap_size = mem_size-mem_start; handle_cnt = full_heap_size/2/(TYPICAL_OBJ_SIZE+HANDLE_SIZE); semi_size = (full_heap_size-handle_cnt*HANDLE_SIZE)/2; heapStartA = mem_start+handle_cnt*HANDLE_SIZE; heapStartB = heapStartA+semi_size; // log(""); // log("memory size", mem_size); // log("handle start ", mem_start); // log("heap start (toSpace)", heapStartA); // log("fromSpace", heapStartB); // log("heap size (bytes)", semi_size*4*2); useA = true; copyPtr = heapStartA; allocPtr = copyPtr+semi_size; toSpace = heapStartA; fromSpace = heapStartB; freeList = 0; useList = 0; greyList = GREY_END; for (int i=0; i<handle_cnt; ++i) { int ref = mem_start+i*HANDLE_SIZE; // pointer to former freelist head Native.wrMem(freeList, ref+OFF_NEXT); // mark handle as free Native.wrMem(0, ref+OFF_PTR); freeList = ref; Native.wrMem(0, ref+OFF_GREY); Native.wrMem(0, ref+OFF_SPACE); } // clean the heap int end = heapStartA+2*semi_size; for (int i=heapStartA; i<end; ++i) { Native.wrMem(0, i); } concurrentGc = false; // allocate the monitor mutex = new Object(); } public static Object getMutex() { return mutex; } /** * Add object to the gray list/stack * @param ref */ static void push(int ref) { // null pointer check is in the following handle check // Only objects that are referenced by a handle in the // handle area are considered for GC. // Null pointer and references to static strings are not // investigated. if (ref<mem_start || ref>=mem_start+handle_cnt*HANDLE_SIZE) { return; } // does the reference point to a handle start? // TODO: happens in concurrent if ((ref&0x7)!=0) { // log("a not aligned handle"); return; } synchronized (mutex) { // Is this handle on the free list? // Is possible when using conservative stack scanning if (Native.rdMem(ref+OFF_PTR)==0) { // TODO: that happens in concurrent! // log("push of a handle with 0 at OFF_PRT!", ref); return; } // Is it black? // Can happen from a left over from the last GC cycle, can it? // -- it's checked in the write barrier // -- but not in mark.... if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // log("push: allready in toSpace"); return; } // only objects not allready in the grey list // are added if (Native.rdMem(ref+OFF_GREY)==0) { // pointer to former gray list head Native.wrMem(greyList, ref+OFF_GREY); greyList = ref; } } } /** * switch from-space and to-space */ static void flip() { synchronized (mutex) { if (greyList!=GREY_END) log("GC: grey list not empty"); useA = !useA; if (useA) { copyPtr = heapStartA; fromSpace = heapStartB; toSpace = heapStartA; } else { copyPtr = heapStartB; fromSpace = heapStartA; toSpace = heapStartB; } allocPtr = copyPtr+semi_size; } } /** * Scan all thread stacks atomic. * */ static void getStackRoots() { int i, j, cnt; // only pushing stack roots need to be atomic synchronized (mutex) { // add complete stack of the current thread to the root list // roots = GCStkWalk.swk(RtThreadImpl.getActive(),true,false); i = Native.getSP(); for (j = Const.STACK_OFF; j <= i; ++j) { // disable the if when not using gc stack info // if (roots[j - Const.STACK_OFF] == 1) { push(Native.rdIntMem(j)); // } } // Stacks from the other threads cnt = RtThreadImpl.getCnt(); for (i = 0; i < cnt; ++i) { if (i != RtThreadImpl.getActive()) { int[] mem = RtThreadImpl.getStack(i); // sp starts at Const.STACK_OFF int sp = RtThreadImpl.getSP(i) - Const.STACK_OFF; // roots = GCStkWalk.swk(i, false, false); for (j = 0; j <= sp; ++j) { // disable the if when not using gc stack info // if (roots[j] == 1) { push(mem[j]); // } } } } } } /** * Scan all static fields * */ private static void getStaticRoots() { int i; // add static refs to root list int addr = Native.rdMem(addrStaticRefs); int cnt = Native.rdMem(addrStaticRefs+1); for (i=0; i<cnt; ++i) { push(Native.rdMem(addr+i)); } } static void markAndCopy() { int i, ref; - getStaticRoots(); if (!concurrentGc) { getStackRoots(); } + getStaticRoots(); for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } } /** * Sweep through the 'old' use list and move garbage to free list. */ static void sweepHandles() { int ref; synchronized (mutex) { ref = useList; // get start of the list useList = 0; // new uselist starts empty } while (ref!=0) { // read next element, as it is destroyed // by addTo*List() int next = Native.rdMem(ref+OFF_NEXT); synchronized (mutex) { // a BLACK one if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // add to used list Native.wrMem(useList, ref+OFF_NEXT); useList = ref; // a WHITE one } else { // pointer to former freelist head Native.wrMem(freeList, ref+OFF_NEXT); freeList = ref; // mark handle as free Native.wrMem(0, ref+OFF_PTR); } } ref = next; } } /** * Clean the from-space */ static void zapSemi() { // clean the from-space to prepare for the next // flip int end = fromSpace+semi_size; for (int i=fromSpace; i<end; ++i) { Native.wrMem(0, i); } // for tests clean also the remainig memory in the to-space // synchronized (mutex) { // for (int i=copyPtr; i<allocPtr; ++i) { // Native.wrMem(0, i); // } // } } public static void setConcurrent() { concurrentGc = true; } static void gc_alloc() { log(""); log("GC allocation triggered"); if (USE_SCOPES) { log("No GC when scopes are used"); System.exit(1); } if (concurrentGc) { log("meaning out of memory for RT-GC"); System.exit(1); } else { gc(); } } public static void gc() { // log("GC called - free memory:", freeMemory()); flip(); markAndCopy(); sweepHandles(); zapSemi(); // log("GC end - free memory:",freeMemory()); } static int free() { return allocPtr-copyPtr; } // TODO this has to be exchanged on a thread switch // TODO add the javax.realtime classes to the CVS static Scope currentArea; public static Scope getCurrentArea() { return currentArea; } public static void setCurrentArea(Scope sc) { currentArea = sc; } /** * Size of scratchpad memory in 32-bit words * @return */ public static int getScratchpadSize() { return Startup.spm_size; } /** * Allocate a new Object. Invoked from JVM.f_new(cons); * @param cons pointer to class struct * @return address of the handle */ static int newObject(int cons) { int size = Native.rdMem(cons); // instance size if (USE_SCOPES) { // allocate in scope Scope sc = currentArea; if (sc!=null) { int rem = sc.backingStore.length - sc.allocPtr; if (size+2 > rem) { log("Out of memory in scoped memory"); System.exit(1); } int ref = sc.allocPtr; sc.allocPtr += size+2; int ptr = Native.toInt(sc.backingStore); ptr = Native.rdMem(ptr); ptr += ref; sc.backingStore[ref] = ptr+2; sc.backingStore[ref+1] = cons+Const.CLASS_HEADR; return ptr; } } // that's the stop-the-world GC synchronized (mutex) { if (copyPtr+size >= allocPtr) { gc_alloc(); if (copyPtr+size >= allocPtr) { // still not enough memory log("Out of memory error!"); System.exit(1); } } } synchronized (mutex) { if (freeList==0) { log("Run out of handles in new Object!"); // is this a good place to call gc???? // better check available handles on newObject gc_alloc(); if (freeList==0) { log("Still out of handles!"); System.exit(1); } } } int ref; synchronized (mutex) { // we allocate from the upper part allocPtr -= size; // get one from free list ref = freeList; // if ((ref&0x07)!=0) { // log("getHandle problem"); // } // if (Native.rdMem(ref+OFF_PTR)!=0) { // log("getHandle not free"); // } freeList = Native.rdMem(ref+OFF_NEXT); // and add it to use list Native.wrMem(useList, ref+OFF_NEXT); useList = ref; // pointer to real object, also marks it as non free Native.wrMem(allocPtr, ref); // +OFF_PTR // should be from the class info Native.wrMem(size, ref+OFF_SIZE); // mark it as BLACK - means it will be in toSpace Native.wrMem(toSpace, ref+OFF_SPACE); // TODO: should not be necessary - now just for sure Native.wrMem(0, ref+OFF_GREY); // BTW: when we create mutex we synchronize on the not yet // created Object! // ref. flags used for array marker Native.wrMem(IS_OBJ, ref+OFF_TYPE); // pointer to method table in the handle Native.wrMem(cons+Const.CLASS_HEADR, ref+OFF_MTAB_ALEN); } return ref; } static int newArray(int size, int type) { int arrayLength = size; // long or double array if((type==11)||(type==7)) size <<= 1; // reference array type is 1 (our convention) if (USE_SCOPES) { // allocate in scope Scope sc = currentArea; if (sc!=null) { int rem = sc.backingStore.length - sc.allocPtr; if (size+2 > rem) { log("Out of memory in scoped memory"); System.exit(1); } int ref = sc.allocPtr; sc.allocPtr += size+2; int ptr = Native.toInt(sc.backingStore); ptr = Native.rdMem(ptr); ptr += ref; sc.backingStore[ref] = ptr+2; sc.backingStore[ref+1] = arrayLength; return ptr; } } synchronized (mutex) { if (copyPtr+size >= allocPtr) { gc_alloc(); if (copyPtr+size >= allocPtr) { // still not enough memory log("Out of memory error!"); System.exit(1); } } } synchronized (mutex) { if (freeList==0) { log("Run out of handles in new array!"); // is this a good place to call gc???? // better check available handles on newObject gc_alloc(); if (freeList==0) { log("Still out of handles!"); System.exit(1); } } } int ref; synchronized (mutex) { // we allocate from the upper part allocPtr -= size; // get one from free list ref = freeList; // if ((ref&0x07)!=0) { // log("getHandle problem"); // } // if (Native.rdMem(ref+OFF_PTR)!=0) { // log("getHandle not free"); // } freeList = Native.rdMem(ref+OFF_NEXT); // and add it to use list Native.wrMem(useList, ref+OFF_NEXT); useList = ref; // pointer to real object, also marks it as non free Native.wrMem(allocPtr, ref); // +OFF_PTR // should be from the class info Native.wrMem(size, ref+OFF_SIZE); // mark it as BLACK - means it will be in toSpace Native.wrMem(toSpace, ref+OFF_SPACE); // TODO: should not be necessary - now just for sure Native.wrMem(0, ref+OFF_GREY); // ref. flags used for array marker Native.wrMem(type, ref+OFF_TYPE); // array length in the handle Native.wrMem(arrayLength, ref+OFF_MTAB_ALEN); } return ref; } /** * @return */ public static int freeMemory() { return free()*4; } /** * @return */ public static int totalMemory() { return semi_size*4; } /** * Check if a given value is a valid handle. * * This method traverse the list of handles (in use) to check * if the handle provided belong to the list. * * It does *not* check the free handle list. * * One detail: the result may state that a handle to a * (still unknown garbage) object is valid, in case * the object is not reachable but still present * on the use list. * This happens in case the object becomes unreachable * during execution, but GC has not reclaimed it yet. * Anyway, it's still a valid object handle. * * @param handle the value to be checked. * @return */ public static final boolean isValidObjectHandle(int handle) { boolean isValid; int handlePointer; // assume it's not valid and try to show otherwise isValid = false; // synchronize on the GC lock synchronized (mutex) { // start on the first element of the list handlePointer = useList; // traverse the list until the element is found or the list is over while(handlePointer != 0) { if(handle == handlePointer) { // found it! hence, it's a valid handle. Stop the search. isValid = true; break; } // not found yet. Let's go to the next element and try again. handlePointer = Native.rdMem(handlePointer+OFF_NEXT); } } return isValid; } /** * Write barrier for an object field. May be used with regular objects * and reference arrays. * * @param handle the object handle * @param index the field index */ public static final void writeBarrier(int handle, int index) { boolean shouldExecuteBarrier = false; int gcInfo; // log("WriteBarrier: snapshot-at-beginning."); if (handle == 0) { throw new NullPointerException(); } synchronized (GC.mutex) { // ignore objects with size zero (is this correct?) if(Native.rdMem(handle) == 0) { // log("ignore objects with size zero"); return; } // get information on the object type. int type = Native.rdMem(handle + GC.OFF_TYPE); // if it's an object or reference array, execute the barrier if(type == GC.IS_REFARR) { // log("Reference array."); shouldExecuteBarrier = true; } if(type == GC.IS_OBJ) { // log("Regular object."); // get the object GC info from the class structure. gcInfo = Native.rdMem(handle + GC.OFF_MTAB_ALEN) + Const.MTAB2GC_INFO; gcInfo = Native.rdMem(gcInfo); // log("GCInfo field: ", gcInfo); // if the correct bit is set for the field, it may hold a reference. // then, execute the write barrier. if((gcInfo & (0x01 << index)) != 0) { // log("Field can hold a reference. Execute barrier!"); shouldExecuteBarrier = true; } } // execute the write barrier, if necessary. if(shouldExecuteBarrier) { // handle indirection handle = Native.rdMem(handle); // snapshot-at-beginning barrier int oldVal = Native.rdMem(handle+index); // log("Old val: ", oldVal); // if(oldVal != 0) // { // log("Current space: ", Native.rdMem(oldVal+GC.OFF_SPACE)); // } // else // { // log("Current space: NULL object."); // } // log("toSpace: ", GC.toSpace); if (oldVal!=0 && Native.rdMem(oldVal+GC.OFF_SPACE)!=GC.toSpace) { // log("Executing write barrier for old handle: ", handle); GC.push(oldVal); } } // else // { // log("Should not execute the barrier."); // } } } /************************************************************************************************/ static void log(String s, int i) { JVMHelp.wr(s); JVMHelp.wr(" "); JVMHelp.wrSmall(i); JVMHelp.wr("\n"); } static void log(String s) { JVMHelp.wr(s); JVMHelp.wr("\n"); } }
false
true
static void markAndCopy() { int i, ref; getStaticRoots(); if (!concurrentGc) { getStackRoots(); } for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }
static void markAndCopy() { int i, ref; if (!concurrentGc) { getStackRoots(); } getStaticRoots(); for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }
diff --git a/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java b/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java index f4ac7a34b..7124b4fde 100644 --- a/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java +++ b/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java @@ -1,854 +1,855 @@ /** * CustomerHelper.java version: 1.0 * Copyright (c) 2005-2006 Grameen Foundation USA * 1029 Vermont Avenue, NW, Suite 400, Washington DC 20005 * All rights reserved. * Apache License * Copyright (c) 2005-2006 Grameen Foundation USA * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the * License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an explanation of the license * and how it is applied. * */ package org.mifos.application.customer.util.helpers; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.mifos.application.NamedQueryConstants; import org.mifos.application.accounts.util.valueobjects.AccountActionDate; import org.mifos.application.accounts.util.valueobjects.AccountFees; import org.mifos.application.accounts.util.valueobjects.AccountFeesActionDetail; import org.mifos.application.accounts.util.valueobjects.CustomerAccount; import org.mifos.application.configuration.business.ConfigurationIntf; import org.mifos.application.configuration.business.MifosConfiguration; import org.mifos.application.configuration.util.helpers.ConfigurationConstants; import org.mifos.application.customer.center.util.helpers.CenterConstants; import org.mifos.application.customer.center.util.helpers.ValidateMethods; import org.mifos.application.customer.center.util.valueobjects.Center; import org.mifos.application.customer.client.util.valueobjects.Client; import org.mifos.application.customer.dao.CustomerNoteDAO; import org.mifos.application.customer.dao.CustomerUtilDAO; import org.mifos.application.customer.exceptions.CustomerException; import org.mifos.application.customer.group.util.helpers.GroupConstants; import org.mifos.application.customer.group.util.valueobjects.Group; import org.mifos.application.customer.util.valueobjects.Customer; import org.mifos.application.customer.util.valueobjects.CustomerAddressDetail; import org.mifos.application.customer.util.valueobjects.CustomerHierarchy; import org.mifos.application.customer.util.valueobjects.CustomerMeeting; import org.mifos.application.customer.util.valueobjects.CustomerMovement; import org.mifos.application.customer.util.valueobjects.CustomerNote; import org.mifos.application.customer.util.valueobjects.CustomerPosition; import org.mifos.application.customer.util.valueobjects.CustomerPositionDisplay; import org.mifos.application.fees.util.valueobjects.FeeFrequency; import org.mifos.application.fees.util.valueobjects.FeeMaster; import org.mifos.application.fees.util.valueobjects.Fees; import org.mifos.application.master.util.valueobjects.PositionMaster; import org.mifos.application.master.util.valueobjects.StatusMaster; import org.mifos.application.meeting.util.valueobjects.Meeting; import org.mifos.application.personnel.dao.PersonnelDAO; import org.mifos.application.personnel.util.valueobjects.Personnel; import org.mifos.application.personnel.util.valueobjects.PersonnelMaster; import org.mifos.framework.components.configuration.business.Configuration; import org.mifos.framework.components.repaymentschedule.RepaymentSchedule; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleConstansts; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleFactory; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleHelper; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleIfc; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleInputsIfc; import org.mifos.framework.dao.helpers.MasterDataRetriever; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.HibernateProcessException; import org.mifos.framework.exceptions.SystemException; import org.mifos.framework.hibernate.helper.HibernateUtil; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.struts.tags.DateHelper; import org.mifos.framework.util.valueobjects.Context; import org.mifos.framework.util.valueobjects.SearchResults; /** * This class is a helper class to customer (i.e. client/group/center). * This includes commom methods for customer that can be used by client,group or center. * @author navitas */ public class CustomerHelper { private ConfigurationIntf labelConfig=MifosConfiguration.getInstance(); public Date getCurrentDate(){ return new java.sql.Date(new java.util.Date().getTime()); } /** * This method creates a new customer movement object. * @return instance of CustomerMovement */ public CustomerMovement createCustomerMovement(Customer customer, Date startDate, short status, short userId)throws ApplicationException,SystemException{ CustomerMovement movement = new CustomerMovement(); movement.setCustomer(customer); if(startDate!=null) movement.setStartDate(startDate); else movement.setStartDate(new Date(new java.util.Date().getTime())); movement.setStatus(status); movement.setEndDate(null); movement.setOffice(customer.getOffice()); movement.setPersonnel(new PersonnelDAO().getUser(userId)); return movement; } /** * This method retrieves the list of programs that can be assigned to the group * @return The list of programs * @throws ApplicationException * @throws SystemException */ public SearchResults getProgramMaster(short localeId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_PROGRAM, GroupConstants.PROGRAMS_SET); masterDataRetriever.setParameter("localeId",localeId); return masterDataRetriever.retrieve(); } /** * This method return the count of customers in a office * @param officeId * @return customer count * @throws ApplicationException * @throws SystemException */ public int getCustomerCountInOffice(short officeId) throws ApplicationException,SystemException { Integer count ; Session session = null; try{ session = HibernateUtil.getSession(); Transaction trxn = session.beginTransaction(); Query query = session.createQuery("select count(*) from org.mifos.application.customer.util.valueobjects.Customer customer where customer.office.officeId =:OFFICEID"); query.setShort("OFFICEID", officeId); count = (Integer)query.uniqueResult(); trxn.commit(); return count; }catch(HibernateProcessException hpe){ throw hpe; }finally{ HibernateUtil.closeSession(session); } } /** * This method returns the count of customers based on given level * @param levelId * @return customer count * @throws ApplicationException * @throws SystemException */ public int getCustomerCount(short levelId,short officeId)throws ApplicationException,SystemException{ Integer count ; Session session = null; try{ session = HibernateUtil.getSession(); Query query = session.createQuery("select count(*) from org.mifos.application.customer.util.valueobjects.Customer customer where customer.customerLevel.levelId =:LEVELID and customer.office.officeId=:OFFICEID"); query.setShort("LEVELID", levelId); query.setShort("OFFICEID", officeId); count = (Integer)query.uniqueResult(); return count; }catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); }finally{ HibernateUtil.closeSession(session); } } /** * This method returns the name of status configured for a level in the given locale * @param localeId user locale * @param statusId status id * @param levelId customer level * @return string status name * @throws ApplicationException * @throws SystemException */ public String getStatusName(short localeId, short statusId,short levelId)throws ApplicationException,SystemException{ String statusName=null; List<StatusMaster> statusList =(List) new CustomerHelper().getStatusMaster(localeId,statusId,levelId).getValue(); if(statusList!=null){ StatusMaster sm = (StatusMaster)statusList.get(0); statusName= sm.getStatusName(); } return statusName; } /** * This method returns the name of flag * @param flagId customer flag * @param localeId user locale * @return string flag name * @throws ApplicationException * @throws SystemException */ public String getFlagName(short flagId,short localeId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_GET_FLAGNAME, GroupConstants.CURRENT_FLAG); masterDataRetriever.setParameter("flagId",flagId); masterDataRetriever.setParameter("localeId",localeId); SearchResults sr = masterDataRetriever.retrieve(); return (String)((List)sr.getValue()).get(0); } /** * This method tells whether a given flag for the given status is blacklisted or not * @param flagId customer flag * @return true if flag is blacklisted, otherwise false * @throws ApplicationException * @throws SystemException */ public boolean isBlacklisted(short flagId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_IS_BLACKLISTED, GroupConstants.IS_BLACKLISTED); masterDataRetriever.setParameter("flagId",flagId); SearchResults sr = masterDataRetriever.retrieve(); return ((Short)((List)sr.getValue()).get(0)).shortValue()==1?true:false; } /** * This method returns the list of next available status * to which a customer can move as per the customer state flow diagram * @param localeId user locale * @param statusId status id * @param levelId customer level * @return List next applicable status list * @throws ApplicationException * @throws SystemException */ public List getStatusList(short localeId, short status, short levelId, short branchId)throws ApplicationException,SystemException{ List<StatusMaster> statusList = new ArrayList<StatusMaster>(); switch (status){ case GroupConstants.PARTIAL_APPLICATION : if(Configuration.getInstance().getCustomerConfig(branchId).isPendingApprovalStateDefinedForGroup()) statusList.add(getStatusWithFlags(localeId,GroupConstants.PENDING_APPROVAL,levelId)); else statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CANCELLED, levelId)); break; case GroupConstants.PENDING_APPROVAL: statusList.add(getStatusWithFlags(localeId,GroupConstants.PARTIAL_APPLICATION, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CANCELLED, levelId)); break; case GroupConstants.ACTIVE: statusList.add(getStatusWithFlags(localeId,GroupConstants.HOLD, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CLOSED, levelId)); break; case GroupConstants.HOLD: statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CLOSED, levelId)); break; case GroupConstants.CANCELLED: statusList.add(getStatusWithFlags(localeId,GroupConstants.PARTIAL_APPLICATION, levelId)); default: } return statusList; } /** * This method returns flag list associated with passed in status Id * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults flag list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusFlags(short localeId , short statusId , short levelId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_SPECIFIC_STATUS_FLAG, GroupConstants.STATUS_FLAG); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); masterDataRetriever.setParameter("specificStatusId",statusId); return masterDataRetriever.retrieve(); } /** * This method returns list of all available status for a level * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusMaster(short localeId , short statusId, short levelId )throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_SPECIFIC_STATUS, GroupConstants.STATUS); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); masterDataRetriever.setParameter("specificStatusId",statusId); return masterDataRetriever.retrieve(); } /** * This method is the helper method that returns a status along with its assoicated flags * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ private StatusMaster getStatusWithFlags(short locale, short status, short levelId) throws ApplicationException,SystemException{ SearchResults sr = this.getStatusMaster(locale,status, levelId); StatusMaster statusMaster = null; Object obj = sr.getValue(); if(obj!=null){ statusMaster = (StatusMaster)((List)obj).get(0); sr = this.getStatusFlags(locale,status, levelId); obj=sr.getValue(); if(obj!=null){ statusMaster.setFlagList((List)obj); } else{ statusMaster.setFlagList(null); } } return statusMaster; } /** * This method returns List given number of notes for a given customer * @param count number of notes to be returned * @return customerId for which notes has to be retrieved * @throws ApplicationException * @throws SystemException */ public List<CustomerNote> getLatestNotes(int count, Integer customerId)throws ApplicationException,SystemException{ CustomerNoteDAO notesDAO = new CustomerNoteDAO(); return notesDAO.getLatestNotesByCount(count, customerId); } /** * This method is used to retrieve MasterDataRetriver instance * @return instance of MasterDataRetriever * @throws HibernateProcessException */ public MasterDataRetriever getMasterDataRetriever()throws HibernateProcessException{ return new MasterDataRetriever(); } /** * This method returns list of all available status for a level * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusForLevel(short localeId , short levelId )throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_STATUS, GroupConstants.STATUS_LIST); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); return masterDataRetriever.retrieve(); } /*** * This method converts the valueobject to reflect the changes being done on a edit of MFI information. * @param oldClient The details retrieved from the database * @param newClient The MFI details which would ahve been edited * @return */ public Client convertOldClientMFIDetails(Client oldClient , Client newClient){ oldClient.setExternalId(newClient.getExternalId()); oldClient.setTrained(newClient.getTrained()); oldClient.setTrainedDate(newClient.getTrainedDate()); oldClient.setClientConfidential(newClient.getClientConfidential()); oldClient.setCustomerFormedByPersonnel(newClient.getCustomerFormedByPersonnel()); //oldClient.setPersonnel(newClient.getPersonnel()); return oldClient; } /** * This method creates a new customer hierarchy object. It is called whenever a new group is created with * center as its parent or group parent is changed. * @return instance of CustomerHierarchy */ public CustomerHierarchy createCustomerHierarchy(Customer parent, Customer child, Context context){ CustomerHierarchy customerHierarchy = new CustomerHierarchy(); customerHierarchy.setCustomer(child); customerHierarchy.setParentCustomer(parent); customerHierarchy.setStatus(CustomerConstants.ACTIVE_HIERARCHY); customerHierarchy.setEndDate(new java.sql.Date(new java.util.Date().getTime())); customerHierarchy.setStartDate(new java.sql.Date(new java.util.Date().getTime())); customerHierarchy.setUpdatedBy(context.getUserContext().getId()); customerHierarchy.setUpdatedDate(new java.sql.Date(new java.util.Date().getTime())); return customerHierarchy; } /** * This method creates a new customer hierarchy object. It is called whenever a new group is created with * center as its parent or group parent is changed. * @return instance of CustomerHierarchy */ public CustomerMovement createCustomerMovement(Customer customer , Date startDate){ CustomerMovement customerMovement = new CustomerMovement(); customerMovement.setCustomer(customer); customerMovement.setStatus(CustomerConstants.ACTIVE_HIERARCHY); customerMovement.setStartDate(startDate); customerMovement.setOffice(customer.getOffice()); customerMovement.setPersonnel(customer.getPersonnel()); return customerMovement; } /** * This method creates a new SearchResults object with values as passed in parameters * @param resultName the name with which framework will put resultvalue in request * @param resultValue that need to be put in request * @return SearchResults instance */ public SearchResults getResultObject(String resultName, Object resultValue){ SearchResults result = new SearchResults(); result.setResultName(resultName); result.setValue(resultValue); return result; } /*** * Concatenates all the names together * @param firstName * @param middleName * @param secondLastName * @param lastName * @return */ public String setDisplayNames(String firstName, String middleName, String secondLastName, String lastName) { StringBuilder displayName = new StringBuilder(); displayName.append(firstName); if(!ValidateMethods.isNullOrBlank(middleName)){ displayName.append(CustomerConstants.BLANK); displayName.append(middleName ); } if(!ValidateMethods.isNullOrBlank(secondLastName)){ displayName.append(CustomerConstants.BLANK); displayName.append(secondLastName); } if(!ValidateMethods.isNullOrBlank(lastName)){ displayName.append(CustomerConstants.BLANK); displayName.append(lastName); } return displayName.toString().trim(); } /** * This method is helper method that sets the personnel age in request * @param request Contains the request parameters */ public int calculateAge(Date date){ int age = DateHelper.DateDiffInYears(date); return age; } /** * Generates the ID for the client using ID Generator. * @return * @throws SystemException * @throws ApplicationException */ public String generateSystemId(Short officeId , String officeGlobalNum)throws SystemException,ApplicationException{ int maxCustomerId = 0; maxCustomerId = new CustomerUtilDAO().getMaxCustomerId(officeId); String systemId = IdGenerator.generateSystemId(officeGlobalNum , maxCustomerId); return systemId; } /** * This is the helper method to check for extra date validations needed at the time of create preview * @param personnelStatus */ public boolean isValidDOB(String dob ,Locale mfiLocale){ java.sql.Date sqlDOB=null; boolean isValidDate = true; if(!ValidateMethods.isNullOrBlank(dob)) { sqlDOB=DateHelper.getLocaleDate(mfiLocale,dob); Calendar currentCalendar = new GregorianCalendar(); int year=currentCalendar.get(Calendar.YEAR); int month=currentCalendar.get(Calendar.MONTH); int day=currentCalendar.get(Calendar.DAY_OF_MONTH); currentCalendar = new GregorianCalendar(year,month,day); java.sql.Date currentDate=new java.sql.Date(currentCalendar.getTimeInMillis()); if(currentDate.compareTo(sqlDOB) < 0 ) { isValidDate= false; } } return isValidDate; } /** * This method concatenates differnt address lines and forms one line of address * @param addressDetails CustomerAddressDetail * @return string single line address */ public String getDisplayAddress(CustomerAddressDetail addressDetails){ String displayAddress=""; if(!isNullOrBlank(addressDetails.getLine1())){ displayAddress+=addressDetails.getLine1(); } if(!isNullOrBlank(addressDetails.getLine2())&&!isNullOrBlank(addressDetails.getLine1())){ displayAddress+=", "+ addressDetails.getLine2(); } else if(!isNullOrBlank(addressDetails.getLine2())){ displayAddress+=addressDetails.getLine2(); } if(!isNullOrBlank(addressDetails.getLine3())&&!isNullOrBlank(addressDetails.getLine2())||(!isNullOrBlank(addressDetails.getLine3())&&!isNullOrBlank(addressDetails.getLine1()))){ displayAddress+=", "+ addressDetails.getLine3(); } else if(!isNullOrBlank(addressDetails.getLine3())){ displayAddress+=addressDetails.getLine3(); } return displayAddress; } /*** * This method checks if a particuar value is either null or blank * @param value the value that has to be checked as to whether it is null or blank * @return true or false as to whether the value passed was null or blank */ public static boolean isNullOrBlank(String value){ boolean isValueNull = false; if(value == null || value.trim().equals(CenterConstants.BLANK)){ isValueNull = true; } return isValueNull; } public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ + meeting = customerMeeting.getMeeting(); try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); if(accountFeesSet!=null) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ for(AccountFees accountFees : accountFeesSet){ accountFees.setLastAppliedDate(null); } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } } public void attachMeetingDetails(Customer customer,Session session,CustomerMeeting customerMeeting) throws ApplicationException,SystemException { //Customer customer = (Customer)context.getValueObject(); Meeting meeting =null ; // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting){ meeting = customerMeeting.getMeeting(); // Session session = null; //Transaction trxn = null; try { //session = HibernateUtil.getSession(); //trxn = session.beginTransaction(); /* Customer vo = (Customer)session.get(Customer.class,customer.getCustomerId()); if(vo.getCustomerAccounts()!=null){ Iterator accountsIterator = vo.getCustomerAccounts().iterator(); while(accountsIterator.hasNext()){ Account account = (Account)accountsIterator.next(); if(account.getAccountTypeId().shortValue()== new Short(AccountTypes.CUSTOMERACCOUNT).shortValue()){ vo.setCustomerAccount((CustomerAccount)account); break; } } } CustomerAccount customerAccount=vo.getCustomerAccount(); Set<AccountFees> accountFeesSet=null; if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); // System.out.println("In Account Fees-----@@@@^^^^^^^^^&&&&&&&&&&**************" + "**********#################!!!!!!!!!!------"+accountFeesSet.size()); for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } }*/ //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); //repaymntScheduleInputs.setAccountFee(accountFeesSet); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //context.addAttribute(new SearchResults("AccountActionDate",accntActionDateSet)); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); session.save(accountActionDate); } } //trxn.commit(); }catch (Exception hpe) { throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe); } } } /** * This method returns true if there is any accountFee with null or zero amnt. * it checks if the fees id is not null , then amount should not be null. * @return true or false */ public boolean isAnyAccountFeesWithoutAmnt(List<FeeMaster> adminFeeList , List<FeeMaster> selectedFeeList ) { //check if any administrative fee amount is null if(null!=adminFeeList && adminFeeList.size()>0){ for(int index=0;index<adminFeeList.size();index++ ){ if(adminFeeList.get(index).getCheckedFee()==null ||(adminFeeList.get(index).getCheckedFee()!=null &&adminFeeList.get(index).getCheckedFee().shortValue()!=1)){ if (adminFeeList.get(index).getRateOrAmount()==null ||adminFeeList.get(index).getRateOrAmount()==0.0){ return true; } } } } //check if any additional fee amount is null if(null!=selectedFeeList && selectedFeeList.size()>0){ for(int index=0;index<selectedFeeList.size();index++ ){ if(selectedFeeList.get(index).getFeeId()!=null && selectedFeeList.get(index).getFeeId().shortValue()!=0 ){ if (selectedFeeList.get(index).getRateOrAmount()==null ||selectedFeeList.get(index).getRateOrAmount()==0.0){ return true; } } } } return false; } /** * This method prepares a list of CustomerPositionDisplay that tells which position is assigned to which customer. * @param group * @return List of CustomerPositionDisplay * @throws ApplicationExcpetion * @throws SystemExcpetion */ public List loadCustomerPositions(Customer customer, short localeId,List positionMaster)throws ApplicationException,SystemException{ List<CustomerPositionDisplay> customerPositions = new ArrayList<CustomerPositionDisplay>(); //SearchResults sr = new GroupHelper().getPositionsMaster(localeId); //List positionMaster =(List) sr.getValue(); Set positionsSet = customer.getCustomerPositions(); if(positionMaster!=null && positionsSet!=null){ PositionMaster pm=null; CustomerPosition cp=null; CustomerPositionDisplay cpdisplay=null; Iterator posMaster=positionMaster.iterator(); Iterator custPos=null; while(posMaster.hasNext()){ pm=(PositionMaster)posMaster.next(); cpdisplay = new CustomerPositionDisplay(); cpdisplay.setPositionId(pm.getPositionId()); cpdisplay.setPositionName(pm.getPositionName()); custPos=positionsSet.iterator(); while(custPos.hasNext()){ cp=(CustomerPosition)custPos.next(); if(cp.getPositionId().intValue()==pm.getPositionId().intValue()){ cpdisplay.setCustomerName(cp.getCustomerName()); cpdisplay.setCustomerId(cp.getCustomerId()); } } customerPositions.add(cpdisplay); } } return customerPositions; } public Personnel getFormedByLO(Context context, short personnelId) { Personnel loanOfficer = new Personnel(); Iterator iteratorLO=((List)context.getSearchResultBasedOnName(CustomerConstants.FORMEDBY_LOAN_OFFICER_LIST).getValue()).iterator(); //Obtaining the name of the selected loan officer from the master list of loan officers while (iteratorLO.hasNext()){ PersonnelMaster lo=(PersonnelMaster)iteratorLO.next(); if(lo.getPersonnelId().shortValue()==personnelId){ loanOfficer.setPersonnelId(lo.getPersonnelId()); loanOfficer.setDisplayName(lo.getDisplayName()); loanOfficer.setVersionNo(lo.getVersionNo()); } } return loanOfficer; } }
true
true
public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); if(accountFeesSet!=null) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ for(AccountFees accountFees : accountFeesSet){ accountFees.setLastAppliedDate(null); } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } }
public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ meeting = customerMeeting.getMeeting(); try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); if(accountFeesSet!=null) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ for(AccountFees accountFees : accountFeesSet){ accountFees.setLastAppliedDate(null); } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } }
diff --git a/src/com/android/calendar/EditEvent.java b/src/com/android/calendar/EditEvent.java index 40360936..43d99a37 100644 --- a/src/com/android/calendar/EditEvent.java +++ b/src/com/android/calendar/EditEvent.java @@ -1,2335 +1,2335 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar; import static android.provider.Calendar.EVENT_BEGIN_TIME; import static android.provider.Calendar.EVENT_END_TIME; import com.android.calendar.TimezoneAdapter.TimezoneRow; import com.android.common.Rfc822InputFilter; import com.android.common.Rfc822Validator; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.AsyncQueryHandler; import android.content.ContentProviderOperation; import android.content.ContentProviderOperation.Builder; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.pim.EventRecurrence; import android.provider.Calendar.Attendees; import android.provider.Calendar.Calendars; import android.provider.Calendar.Events; import android.provider.Calendar.Reminders; import android.text.Editable; import android.text.InputFilter; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.util.Rfc822Token; import android.text.util.Rfc822Tokenizer; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.MultiAutoCompleteTextView; import android.widget.ResourceCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Formatter; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Locale; import java.util.TimeZone; public class EditEvent extends Activity implements View.OnClickListener, DialogInterface.OnCancelListener, DialogInterface.OnClickListener { private static final String TAG = "EditEvent"; private static final boolean DEBUG = false; /** * This is the symbolic name for the key used to pass in the boolean * for creating all-day events that is part of the extra data of the intent. * This is used only for creating new events and is set to true if * the default for the new event should be an all-day event. */ public static final String EVENT_ALL_DAY = "allDay"; private static final int MAX_REMINDERS = 5; private static final int MENU_GROUP_REMINDER = 1; private static final int MENU_GROUP_SHOW_OPTIONS = 2; private static final int MENU_GROUP_HIDE_OPTIONS = 3; private static final int MENU_ADD_REMINDER = 1; private static final int MENU_SHOW_EXTRA_OPTIONS = 2; private static final int MENU_HIDE_EXTRA_OPTIONS = 3; private static final String[] EVENT_PROJECTION = new String[] { Events._ID, // 0 Events.TITLE, // 1 Events.DESCRIPTION, // 2 Events.EVENT_LOCATION, // 3 Events.ALL_DAY, // 4 Events.HAS_ALARM, // 5 Events.CALENDAR_ID, // 6 Events.DTSTART, // 7 Events.DURATION, // 8 Events.EVENT_TIMEZONE, // 9 Events.RRULE, // 10 Events._SYNC_ID, // 11 Events.TRANSPARENCY, // 12 Events.VISIBILITY, // 13 Events.OWNER_ACCOUNT, // 14 Events.HAS_ATTENDEE_DATA, // 15 }; private static final int EVENT_INDEX_ID = 0; private static final int EVENT_INDEX_TITLE = 1; private static final int EVENT_INDEX_DESCRIPTION = 2; private static final int EVENT_INDEX_EVENT_LOCATION = 3; private static final int EVENT_INDEX_ALL_DAY = 4; private static final int EVENT_INDEX_HAS_ALARM = 5; private static final int EVENT_INDEX_CALENDAR_ID = 6; private static final int EVENT_INDEX_DTSTART = 7; private static final int EVENT_INDEX_DURATION = 8; private static final int EVENT_INDEX_TIMEZONE = 9; private static final int EVENT_INDEX_RRULE = 10; private static final int EVENT_INDEX_SYNC_ID = 11; private static final int EVENT_INDEX_TRANSPARENCY = 12; private static final int EVENT_INDEX_VISIBILITY = 13; private static final int EVENT_INDEX_OWNER_ACCOUNT = 14; private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 15; private static final String[] CALENDARS_PROJECTION = new String[] { Calendars._ID, // 0 Calendars.DISPLAY_NAME, // 1 Calendars.OWNER_ACCOUNT, // 2 Calendars.COLOR, // 3 }; private static final int CALENDARS_INDEX_DISPLAY_NAME = 1; private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2; private static final int CALENDARS_INDEX_COLOR = 3; private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" + Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1"; private static final String[] REMINDERS_PROJECTION = new String[] { Reminders._ID, // 0 Reminders.MINUTES, // 1 }; private static final int REMINDERS_INDEX_MINUTES = 1; private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" + Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" + Reminders.METHOD_DEFAULT + ")"; private static final String[] ATTENDEES_PROJECTION = new String[] { Attendees.ATTENDEE_NAME, // 0 Attendees.ATTENDEE_EMAIL, // 1 }; private static final int ATTENDEES_INDEX_NAME = 0; private static final int ATTENDEES_INDEX_EMAIL = 1; private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=? AND " + Attendees.ATTENDEE_RELATIONSHIP + "<>" + Attendees.RELATIONSHIP_ORGANIZER; private static final String ATTENDEES_DELETE_PREFIX = Attendees.EVENT_ID + "=? AND " + Attendees.ATTENDEE_EMAIL + " IN ("; private static final int DOES_NOT_REPEAT = 0; private static final int REPEATS_DAILY = 1; private static final int REPEATS_EVERY_WEEKDAY = 2; private static final int REPEATS_WEEKLY_ON_DAY = 3; private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4; private static final int REPEATS_MONTHLY_ON_DAY = 5; private static final int REPEATS_YEARLY = 6; private static final int REPEATS_CUSTOM = 7; private static final int MODIFY_UNINITIALIZED = 0; private static final int MODIFY_SELECTED = 1; private static final int MODIFY_ALL = 2; private static final int MODIFY_ALL_FOLLOWING = 3; private static final int DAY_IN_SECONDS = 24 * 60 * 60; private int mFirstDayOfWeek; // cached in onCreate private Uri mUri; private Cursor mEventCursor; private Cursor mCalendarsCursor; private Button mStartDateButton; private Button mEndDateButton; private Button mStartTimeButton; private Button mEndTimeButton; private Button mSaveButton; private Button mDeleteButton; private Button mDiscardButton; private Button mTimezoneButton; private CheckBox mAllDayCheckBox; private Spinner mCalendarsSpinner; private Spinner mRepeatsSpinner; private Spinner mAvailabilitySpinner; private Spinner mVisibilitySpinner; private TextView mTitleTextView; private TextView mLocationTextView; private TextView mDescriptionTextView; private TextView mTimezoneTextView; private TextView mTimezoneFooterView; private TextView mStartTimeHome; private TextView mStartDateHome; private TextView mEndTimeHome; private TextView mEndDateHome; private View mRemindersSeparator; private LinearLayout mRemindersContainer; private LinearLayout mExtraOptions; private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>(); private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); private Rfc822Validator mEmailValidator; private MultiAutoCompleteTextView mAttendeesList; private EmailAddressAdapter mAddressAdapter; private TimezoneAdapter mTimezoneAdapter; private String mOriginalAttendees = ""; // Used to control the visibility of the Guests textview. Default to true private boolean mHasAttendeeData = true; private EventRecurrence mEventRecurrence = new EventRecurrence(); private String mRrule; private boolean mCalendarsQueryComplete; private boolean mSaveAfterQueryComplete; private ProgressDialog mLoadingCalendarsDialog; private AlertDialog mNoCalendarsDialog; private AlertDialog mTimezoneDialog; private ContentValues mInitialValues; private String mOwnerAccount; /** * If the repeating event is created on the phone and it hasn't been * synced yet to the web server, then there is a bug where you can't * delete or change an instance of the repeating event. This case * can be detected with mSyncId. If mSyncId == null, then the repeating * event has not been synced to the phone, in which case we won't allow * the user to change one instance. */ private String mSyncId; private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0); private ArrayList<Integer> mReminderValues; private ArrayList<String> mReminderLabels; private Time mStartTime; private Time mEndTime; private String mTimezone; private int mModification = MODIFY_UNINITIALIZED; private int mDefaultReminderMinutes; private DeleteEventHelper mDeleteEventHelper; private QueryHandler mQueryHandler; private static StringBuilder mSB = new StringBuilder(50); private static Formatter mF = new Formatter(mSB, Locale.getDefault()); // This is here in case we need to update tz info later private Runnable mUpdateTZ = null; /* This class is used to update the time buttons. */ private class TimeListener implements OnTimeSetListener { private View mView; public TimeListener(View view) { mView = view; } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time endTime = mEndTime; // Cache the start and end millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long endMillis; if (mView == mStartTimeButton) { // The start time was changed. int hourDuration = endTime.hour - startTime.hour; int minuteDuration = endTime.minute - startTime.minute; startTime.hour = hourOfDay; startTime.minute = minute; startMillis = startTime.normalize(true); // Also update the end time to keep the duration constant. endTime.hour = hourOfDay + hourDuration; endTime.minute = minute + minuteDuration; } else { // The end time was changed. startMillis = startTime.toMillis(true); endTime.hour = hourOfDay; endTime.minute = minute; // Move to the next day if the end time is before the start time. if (endTime.before(startTime)) { endTime.monthDay = startTime.monthDay + 1; } } endMillis = endTime.normalize(true); setDate(mEndDateButton, endMillis); setTime(mStartTimeButton, startMillis); setTime(mEndTimeButton, endMillis); updateHomeTime(); } } private class TimeClickListener implements View.OnClickListener { private Time mTime; public TimeClickListener(Time time) { mTime = time; } public void onClick(View v) { new TimePickerDialog(EditEvent.this, new TimeListener(v), mTime.hour, mTime.minute, DateFormat.is24HourFormat(EditEvent.this)).show(); } } private class DateListener implements OnDateSetListener { View mView; public DateListener(View view) { mView = view; } public void onDateSet(DatePicker view, int year, int month, int monthDay) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time endTime = mEndTime; // Cache the start and end millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long endMillis; if (mView == mStartDateButton) { // The start date was changed. int yearDuration = endTime.year - startTime.year; int monthDuration = endTime.month - startTime.month; int monthDayDuration = endTime.monthDay - startTime.monthDay; startTime.year = year; startTime.month = month; startTime.monthDay = monthDay; startMillis = startTime.normalize(true); // Also update the end date to keep the duration constant. endTime.year = year + yearDuration; endTime.month = month + monthDuration; endTime.monthDay = monthDay + monthDayDuration; endMillis = endTime.normalize(true); // If the start date has changed then update the repeats. populateRepeats(); } else { // The end date was changed. startMillis = startTime.toMillis(true); endTime.year = year; endTime.month = month; endTime.monthDay = monthDay; endMillis = endTime.normalize(true); // Do not allow an event to have an end time before the start time. if (endTime.before(startTime)) { endTime.set(startTime); endMillis = startMillis; } } setDate(mStartDateButton, startMillis); setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); // In case end time had to be reset updateHomeTime(); } } private class DateClickListener implements View.OnClickListener { private Time mTime; public DateClickListener(Time time) { mTime = time; } public void onClick(View v) { new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year, mTime.month, mTime.monthDay).show(); } } static private class CalendarsAdapter extends ResourceCursorAdapter { public CalendarsAdapter(Context context, Cursor c) { super(context, R.layout.calendars_item, c); setDropDownViewResource(R.layout.calendars_dropdown_item); } @Override public void bindView(View view, Context context, Cursor cursor) { View colorBar = view.findViewById(R.id.color); if (colorBar != null) { colorBar.setBackgroundDrawable( Utils.getColorChip(cursor.getInt(CALENDARS_INDEX_COLOR))); } TextView name = (TextView) view.findViewById(R.id.calendar_name); if (name != null) { String displayName = cursor.getString(CALENDARS_INDEX_DISPLAY_NAME); name.setText(displayName); name.setTextColor(0xFF000000); TextView accountName = (TextView) view.findViewById(R.id.account_name); if(accountName != null) { Resources res = context.getResources(); accountName.setText(cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT)); accountName.setVisibility(TextView.VISIBLE); accountName.setTextColor(res.getColor(R.color.calendar_owner_text_color)); } } } } // This is called if the user clicks on one of the buttons: "Save", // "Discard", or "Delete". This is also called if the user clicks // on the "remove reminder" button. public void onClick(View v) { if (v == mSaveButton) { if (save()) { finish(); } return; } if (v == mDeleteButton) { long begin = mStartTime.toMillis(false /* use isDst */); long end = mEndTime.toMillis(false /* use isDst */); int which = -1; switch (mModification) { case MODIFY_SELECTED: which = DeleteEventHelper.DELETE_SELECTED; break; case MODIFY_ALL_FOLLOWING: which = DeleteEventHelper.DELETE_ALL_FOLLOWING; break; case MODIFY_ALL: which = DeleteEventHelper.DELETE_ALL; break; } mDeleteEventHelper.delete(begin, end, mEventCursor, which); return; } if (v == mDiscardButton) { finish(); return; } // This must be a click on one of the "remove reminder" buttons LinearLayout reminderItem = (LinearLayout) v.getParent(); LinearLayout parent = (LinearLayout) reminderItem.getParent(); parent.removeView(reminderItem); mReminderItems.remove(reminderItem); updateRemindersVisibility(); } // This is called if the user cancels a popup dialog. There are two // dialogs: the "Loading calendars" dialog, and the "No calendars" // dialog. The "Loading calendars" dialog is shown if there is a delay // in loading the calendars (needed when creating an event) and the user // tries to save the event before the calendars have finished loading. // The "No calendars" dialog is shown if there are no syncable calendars. public void onCancel(DialogInterface dialog) { if (dialog == mLoadingCalendarsDialog) { mSaveAfterQueryComplete = false; } else if (dialog == mNoCalendarsDialog) { finish(); } } // This is called if the user clicks on a dialog button. public void onClick(DialogInterface dialog, int which) { if (dialog == mNoCalendarsDialog) { finish(); } else if (dialog == mTimezoneDialog) { if (which >= 0 && which < mTimezoneAdapter.getCount()) { setTimezone(which); updateHomeTime(); dialog.dismiss(); } } } private class QueryHandler extends AsyncQueryHandler { public QueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { // If the query didn't return a cursor for some reason return if (cursor == null) { return; } // If the Activity is finishing, then close the cursor. // Otherwise, use the new cursor in the adapter. if (isFinishing()) { stopManagingCursor(cursor); cursor.close(); } else { mCalendarsCursor = cursor; startManagingCursor(cursor); // Stop the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); // If there are no syncable calendars, then we cannot allow // creating a new event. if (cursor.getCount() == 0) { // Cancel the "loading calendars" dialog if it exists if (mSaveAfterQueryComplete) { mLoadingCalendarsDialog.cancel(); } // Create an error message for the user that, when clicked, // will exit this activity without saving the event. AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this); builder.setTitle(R.string.no_syncable_calendars) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.no_calendars_found) .setPositiveButton(android.R.string.ok, EditEvent.this) .setOnCancelListener(EditEvent.this); mNoCalendarsDialog = builder.show(); return; } int defaultCalendarPosition = findDefaultCalendarPosition(mCalendarsCursor); // populate the calendars spinner CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor); mCalendarsSpinner.setAdapter(adapter); mCalendarsSpinner.setSelection(defaultCalendarPosition); mCalendarsQueryComplete = true; if (mSaveAfterQueryComplete) { mLoadingCalendarsDialog.cancel(); save(); finish(); } // Find user domain and set it to the validator. // TODO: we may want to update this validator if the user actually picks // a different calendar. maybe not. depends on what we want for the // user experience. this may change when we add support for multiple // accounts, anyway. if (mHasAttendeeData && cursor.moveToPosition(defaultCalendarPosition)) { String ownEmail = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); if (ownEmail != null) { String domain = extractDomain(ownEmail); if (domain != null) { mEmailValidator = new Rfc822Validator(domain); mAttendeesList.setValidator(mEmailValidator); } } } } } // Find the calendar position in the cursor that matches calendar in preference private int findDefaultCalendarPosition(Cursor calendarsCursor) { if (calendarsCursor.getCount() <= 0) { return -1; } String defaultCalendar = Utils.getSharedPreference(EditEvent.this, CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, null); if (defaultCalendar == null) { return 0; } int position = 0; calendarsCursor.moveToPosition(-1); while(calendarsCursor.moveToNext()) { if (defaultCalendar.equals(mCalendarsCursor .getString(CALENDARS_INDEX_OWNER_ACCOUNT))) { return position; } position++; } return 0; } } private static String extractDomain(String email) { int separator = email.lastIndexOf('@'); if (separator != -1 && ++separator < email.length()) { return email.substring(separator); } return null; } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.edit_event); boolean newEvent = false; mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek(); mStartTime = new Time(); mEndTime = new Time(); mTimezone = Utils.getTimeZone(this, mUpdateTZ); Intent intent = getIntent(); mUri = intent.getData(); if (mUri != null) { mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null); if (mEventCursor == null || mEventCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); return; } } long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0); long end = intent.getLongExtra(EVENT_END_TIME, 0); String domain = "gmail.com"; boolean allDay = false; if (mEventCursor != null) { // The event already exists so fetch the all-day status mEventCursor.moveToFirst(); mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0; allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String rrule = mEventCursor.getString(EVENT_INDEX_RRULE); if (!allDay) { // only load the event timezone for non-all-day events // otherwise it defaults to device default mTimezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE); } long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID); mOwnerAccount = mEventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT); if (!TextUtils.isEmpty(mOwnerAccount)) { String ownerDomain = extractDomain(mOwnerAccount); if (ownerDomain != null) { domain = ownerDomain; } } // Remember the initial values mInitialValues = new ContentValues(); mInitialValues.put(EVENT_BEGIN_TIME, begin); mInitialValues.put(EVENT_END_TIME, end); mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0); mInitialValues.put(Events.RRULE, rrule); mInitialValues.put(Events.EVENT_TIMEZONE, mTimezone); mInitialValues.put(Events.CALENDAR_ID, calendarId); } else { newEvent = true; // We are creating a new event, so set the default from the // intent (if specified). allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false); // Start the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); // Start a query in the background to read the list of calendars mQueryHandler = new QueryHandler(getContentResolver()); mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION, CALENDARS_WHERE, null /* selection args */, null /* sort order */); } mTimezoneAdapter = new TimezoneAdapter(this, mTimezone); // If the event is all-day, read the times in UTC timezone if (begin != 0) { if (allDay) { mStartTime.timezone = Time.TIMEZONE_UTC; mStartTime.set(begin); mStartTime.timezone = mTimezone; // Calling normalize to calculate isDst mStartTime.normalize(true); } else { mStartTime.timezone = mTimezone; mStartTime.set(begin); } } if (end != 0) { if (allDay) { mEndTime.timezone = Time.TIMEZONE_UTC; mEndTime.set(end); mEndTime.timezone = mTimezone; // Calling normalize to calculate isDst mEndTime.normalize(true); } else { mEndTime.timezone = mTimezone; mEndTime.set(end); } } LayoutInflater inflater = getLayoutInflater(); // cache all the widgets mTitleTextView = (TextView) findViewById(R.id.title); mLocationTextView = (TextView) findViewById(R.id.location); mDescriptionTextView = (TextView) findViewById(R.id.description); mTimezoneTextView = (TextView) findViewById(R.id.timezone_label); mTimezoneFooterView = (TextView) inflater.inflate(R.layout.timezone_footer, null); mStartDateButton = (Button) findViewById(R.id.start_date); mEndDateButton = (Button) findViewById(R.id.end_date); mStartTimeButton = (Button) findViewById(R.id.start_time); mEndTimeButton = (Button) findViewById(R.id.end_time); mStartTimeHome = (TextView) findViewById(R.id.start_time_home); mStartDateHome = (TextView) findViewById(R.id.start_date_home); mEndTimeHome = (TextView) findViewById(R.id.end_time_home); mEndDateHome = (TextView) findViewById(R.id.end_date_home); mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day); mTimezoneButton = (Button) findViewById(R.id.timezone); mCalendarsSpinner = (Spinner) findViewById(R.id.calendars); mRepeatsSpinner = (Spinner) findViewById(R.id.repeats); mAvailabilitySpinner = (Spinner) findViewById(R.id.availability); mVisibilitySpinner = (Spinner) findViewById(R.id.visibility); mRemindersSeparator = findViewById(R.id.reminders_separator); mRemindersContainer = (LinearLayout) findViewById(R.id.reminder_items_container); mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container); if (mHasAttendeeData) { mAddressAdapter = new EmailAddressAdapter(this); mEmailValidator = new Rfc822Validator(domain); mAttendeesList = initMultiAutoCompleteTextView(R.id.attendees); } else { findViewById(R.id.attendees_group).setVisibility(View.GONE); } mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (mEndTime.hour == 0 && mEndTime.minute == 0) { mEndTime.monthDay--; long endMillis = mEndTime.normalize(true); // Do not allow an event to have an end time before the start time. if (mEndTime.before(mStartTime)) { mEndTime.set(mStartTime); endMillis = mEndTime.normalize(true); } setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); } mStartTimeButton.setVisibility(View.GONE); mEndTimeButton.setVisibility(View.GONE); mTimezoneButton.setVisibility(View.GONE); mTimezoneTextView.setVisibility(View.GONE); } else { if (mEndTime.hour == 0 && mEndTime.minute == 0) { mEndTime.monthDay++; long endMillis = mEndTime.normalize(true); setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); } mStartTimeButton.setVisibility(View.VISIBLE); mEndTimeButton.setVisibility(View.VISIBLE); mTimezoneButton.setVisibility(View.VISIBLE); mTimezoneTextView.setVisibility(View.VISIBLE); } updateHomeTime(); } }); if (allDay) { mAllDayCheckBox.setChecked(true); } else { mAllDayCheckBox.setChecked(false); } mSaveButton = (Button) findViewById(R.id.save); mSaveButton.setOnClickListener(this); mDeleteButton = (Button) findViewById(R.id.delete); mDeleteButton.setOnClickListener(this); mDiscardButton = (Button) findViewById(R.id.discard); mDiscardButton.setOnClickListener(this); // Initialize the reminder values array. Resources r = getResources(); String[] strings = r.getStringArray(R.array.reminder_minutes_values); int size = strings.length; ArrayList<Integer> list = new ArrayList<Integer>(size); for (int i = 0 ; i < size ; i++) { list.add(Integer.parseInt(strings[i])); } mReminderValues = list; String[] labels = r.getStringArray(R.array.reminder_minutes_labels); mReminderLabels = new ArrayList<String>(Arrays.asList(labels)); SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this); String durationString = prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0"); mDefaultReminderMinutes = Integer.parseInt(durationString); if (newEvent && mDefaultReminderMinutes != 0) { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, mDefaultReminderMinutes); } long eventId = (mEventCursor == null) ? -1 : mEventCursor.getLong(EVENT_INDEX_ID); ContentResolver cr = getContentResolver(); // Reminders cursor boolean hasAlarm = (mEventCursor != null) && (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0); if (hasAlarm) { Uri uri = Reminders.CONTENT_URI; String where = String.format(REMINDERS_WHERE, eventId); Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null); try { // First pass: collect all the custom reminder minutes (e.g., // a reminder of 8 minutes) into a global list. while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes); } // Second pass: create the reminder spinners reminderCursor.moveToPosition(-1); while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); mOriginalMinutes.add(minutes); EditEvent.addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, minutes); } } finally { reminderCursor.close(); } } updateRemindersVisibility(); // Setup the + Add Reminder Button View.OnClickListener addReminderOnClickListener = new View.OnClickListener() { public void onClick(View v) { addReminder(); } }; ImageButton reminderRemoveButton = (ImageButton) findViewById(R.id.reminder_add); reminderRemoveButton.setOnClickListener(addReminderOnClickListener); mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */); // Attendees cursor if (mHasAttendeeData && eventId != -1) { Uri uri = Attendees.CONTENT_URI; String[] whereArgs = {Long.toString(eventId)}; Cursor attendeeCursor = cr.query(uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, whereArgs, null); try { StringBuilder b = new StringBuilder(); while (attendeeCursor.moveToNext()) { String name = attendeeCursor.getString(ATTENDEES_INDEX_NAME); String email = attendeeCursor.getString(ATTENDEES_INDEX_EMAIL); if (email != null) { if (name != null && name.length() > 0 && !name.equals(email)) { b.append('"').append(name).append("\" "); } b.append('<').append(email).append(">, "); } } if (b.length() > 0) { mOriginalAttendees = b.toString(); mAttendeesList.setText(mOriginalAttendees); } } finally { attendeeCursor.close(); } } if (mEventCursor == null) { // Allow the intent to specify the fields in the event. // This will allow other apps to create events easily. initFromIntent(intent); } } private LinkedHashSet<Rfc822Token> getAddressesFromList(MultiAutoCompleteTextView list) { list.clearComposingText(); LinkedHashSet<Rfc822Token> addresses = new LinkedHashSet<Rfc822Token>(); Rfc822Tokenizer.tokenize(list.getText(), addresses); // validate the emails, out of paranoia. they should already be // validated on input, but drop any invalid emails just to be safe. Iterator<Rfc822Token> addressIterator = addresses.iterator(); while (addressIterator.hasNext()) { Rfc822Token address = addressIterator.next(); if (!mEmailValidator.isValid(address.getAddress())) { Log.w(TAG, "Dropping invalid attendee email address: " + address); addressIterator.remove(); } } return addresses; } // From com.google.android.gm.ComposeActivity private MultiAutoCompleteTextView initMultiAutoCompleteTextView(int res) { MultiAutoCompleteTextView list = (MultiAutoCompleteTextView) findViewById(res); list.setAdapter(mAddressAdapter); list.setTokenizer(new Rfc822Tokenizer()); list.setValidator(mEmailValidator); // NOTE: assumes no other filters are set list.setFilters(sRecipientFilters); return list; } /** * From com.google.android.gm.ComposeActivity * Implements special address cleanup rules: * The first space key entry following an "@" symbol that is followed by any combination * of letters and symbols, including one+ dots and zero commas, should insert an extra * comma (followed by the space). */ private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() }; private void initFromIntent(Intent intent) { String title = intent.getStringExtra(Events.TITLE); if (title != null) { mTitleTextView.setText(title); } String location = intent.getStringExtra(Events.EVENT_LOCATION); if (location != null) { mLocationTextView.setText(location); } String description = intent.getStringExtra(Events.DESCRIPTION); if (description != null) { mDescriptionTextView.setText(description); } int availability = intent.getIntExtra(Events.TRANSPARENCY, -1); if (availability != -1) { mAvailabilitySpinner.setSelection(availability); } int visibility = intent.getIntExtra(Events.VISIBILITY, -1); if (visibility != -1) { mVisibilitySpinner.setSelection(visibility); } String rrule = intent.getStringExtra(Events.RRULE); if (!TextUtils.isEmpty(rrule)) { mRrule = rrule; mEventRecurrence.parse(rrule); } } @Override protected void onResume() { super.onResume(); if (mUri != null) { if (mEventCursor == null || mEventCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); return; } } if (mEventCursor != null) { Cursor cursor = mEventCursor; cursor.moveToFirst(); mRrule = cursor.getString(EVENT_INDEX_RRULE); String title = cursor.getString(EVENT_INDEX_TITLE); String description = cursor.getString(EVENT_INDEX_DESCRIPTION); String location = cursor.getString(EVENT_INDEX_EVENT_LOCATION); int availability = cursor.getInt(EVENT_INDEX_TRANSPARENCY); int visibility = cursor.getInt(EVENT_INDEX_VISIBILITY); if (visibility > 0) { // For now we the array contains the values 0, 2, and 3. We subtract one to match. visibility--; } if (!TextUtils.isEmpty(mRrule) && mModification == MODIFY_UNINITIALIZED) { // If this event has not been synced, then don't allow deleting // or changing a single instance. mSyncId = cursor.getString(EVENT_INDEX_SYNC_ID); mEventRecurrence.parse(mRrule); // If we haven't synced this repeating event yet, then don't // allow the user to change just one instance. int itemIndex = 0; CharSequence[] items; if (mSyncId == null) { if(isFirstEventInSeries()) { // Still display the option so the user knows all events are changing items = new CharSequence[1]; } else { items = new CharSequence[2]; } } else { if(isFirstEventInSeries()) { items = new CharSequence[2]; } else { items = new CharSequence[3]; } items[itemIndex++] = getText(R.string.modify_event); } items[itemIndex++] = getText(R.string.modify_all); // Do one more check to make sure this remains at the end of the list if(!isFirstEventInSeries()) { // TODO Find out why modify all following causes a dup of the first event if // it's operating on the first event. items[itemIndex++] = getText(R.string.modify_all_following); } // Display the modification dialog. new AlertDialog.Builder(this) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); } }) .setTitle(R.string.edit_event_label) .setItems(items, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { mModification = (mSyncId == null) ? MODIFY_ALL : MODIFY_SELECTED; } else if (which == 1) { mModification = (mSyncId == null) ? MODIFY_ALL_FOLLOWING : MODIFY_ALL; } else if (which == 2) { mModification = MODIFY_ALL_FOLLOWING; } // If we are modifying all the events in a // series then disable and ignore the date. if (mModification == MODIFY_ALL) { mStartDateButton.setEnabled(false); mEndDateButton.setEnabled(false); } else if (mModification == MODIFY_SELECTED) { mRepeatsSpinner.setEnabled(false); } } }) .show(); } mTitleTextView.setText(title); mLocationTextView.setText(location); mDescriptionTextView.setText(description); mAvailabilitySpinner.setSelection(availability); mVisibilitySpinner.setSelection(visibility); // This is an existing event so hide the calendar spinner // since we can't change the calendar. View calendarGroup = findViewById(R.id.calendar_group); calendarGroup.setVisibility(View.GONE); } else { // New event if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) { mStartTime.setToNow(); // Round the time to the nearest half hour. mStartTime.second = 0; int minute = mStartTime.minute; if (minute == 0) { // We are already on a half hour increment } else if (minute > 0 && minute <= 30) { mStartTime.minute = 30; } else { mStartTime.minute = 0; mStartTime.hour += 1; } long startMillis = mStartTime.normalize(true /* ignore isDst */); mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS); } // Hide delete button mDeleteButton.setVisibility(View.GONE); } updateRemindersVisibility(); populateWhen(); populateTimezone(); updateHomeTime(); populateRepeats(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem item; item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0, R.string.add_new_reminder); item.setIcon(R.drawable.ic_menu_reminder); item.setAlphabeticShortcut('r'); item = menu.add(MENU_GROUP_SHOW_OPTIONS, MENU_SHOW_EXTRA_OPTIONS, 0, R.string.edit_event_show_extra_options); item.setIcon(R.drawable.ic_menu_show_list); item = menu.add(MENU_GROUP_HIDE_OPTIONS, MENU_HIDE_EXTRA_OPTIONS, 0, R.string.edit_event_hide_extra_options); item.setIcon(R.drawable.ic_menu_show_list); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mReminderItems.size() < MAX_REMINDERS) { menu.setGroupVisible(MENU_GROUP_REMINDER, true); menu.setGroupEnabled(MENU_GROUP_REMINDER, true); } else { menu.setGroupVisible(MENU_GROUP_REMINDER, false); menu.setGroupEnabled(MENU_GROUP_REMINDER, false); } if (mExtraOptions.getVisibility() == View.VISIBLE) { menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, false); menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, true); } else { menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, true); menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, false); } return super.onPrepareOptionsMenu(menu); } private void addReminder() { // TODO: when adding a new reminder, make it different from the // last one in the list (if any). if (mDefaultReminderMinutes == 0) { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, 10 /* minutes */); } else { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, mDefaultReminderMinutes); } updateRemindersVisibility(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD_REMINDER: addReminder(); return true; case MENU_SHOW_EXTRA_OPTIONS: mExtraOptions.setVisibility(View.VISIBLE); return true; case MENU_HIDE_EXTRA_OPTIONS: mExtraOptions.setVisibility(View.GONE); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { // If we are creating a new event, do not create it if the // title, location and description are all empty, in order to // prevent accidental "no subject" event creations. if (mUri != null || !isEmpty()) { if (!save()) { // We cannot exit this activity because the calendars // are still loading. return; } } finish(); } private void populateWhen() { long startMillis = mStartTime.toMillis(false /* use isDst */); long endMillis = mEndTime.toMillis(false /* use isDst */); setDate(mStartDateButton, startMillis); setDate(mEndDateButton, endMillis); setTime(mStartTimeButton, startMillis); setTime(mEndTimeButton, endMillis); mStartDateButton.setOnClickListener(new DateClickListener(mStartTime)); mEndDateButton.setOnClickListener(new DateClickListener(mEndTime)); mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime)); mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime)); } private void populateTimezone() { mTimezoneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTimezoneDialog(); } }); setTimezone(mTimezoneAdapter.getRowById(mTimezone)); } /** * Checks if the start and end times for this event should be * displayed in the Calendar app's time zone as well and * formats and displays them. */ private void updateHomeTime() { String tz = Utils.getTimeZone(this, mUpdateTZ); if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone)) { int flags = DateUtils.FORMAT_SHOW_TIME; boolean is24Format = DateFormat.is24HourFormat(this); if (is24Format) { flags |= DateUtils.FORMAT_24HOUR; } long millisStart = mStartTime.toMillis(false); long millisEnd = mEndTime.toMillis(false); boolean isDSTStart = mStartTime.isDst != 0; boolean isDSTEnd = mEndTime.isDst != 0; // First update the start date and times String tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTStart, TimeZone.SHORT, Locale.getDefault()); StringBuilder time = new StringBuilder(); mSB.setLength(0); time.append(DateUtils.formatDateRange(this, mF, millisStart, millisStart, flags, tz)) .append(" ").append(tzDisplay); mStartTimeHome.setText(time.toString()); flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY; mSB.setLength(0); mStartDateHome.setText(DateUtils.formatDateRange(this, mF, millisStart, millisStart, flags, tz).toString()); // Make any adjustments needed for the end times if (isDSTEnd != isDSTStart) { tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTEnd, TimeZone.SHORT, Locale.getDefault()); } flags = DateUtils.FORMAT_SHOW_TIME; if (is24Format) { flags |= DateUtils.FORMAT_24HOUR; } // Then update the end times time.setLength(0); mSB.setLength(0); time.append(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd, flags, tz)) .append(" ").append(tzDisplay); mEndTimeHome.setText(time.toString()); flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY; mSB.setLength(0); mEndDateHome.setText(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd, flags, tz).toString()); mStartTimeHome.setVisibility(View.VISIBLE); mStartDateHome.setVisibility(View.VISIBLE); mEndTimeHome.setVisibility(View.VISIBLE); mEndDateHome.setVisibility(View.VISIBLE); } else { mStartTimeHome.setVisibility(View.GONE); mStartDateHome.setVisibility(View.GONE); mEndTimeHome.setVisibility(View.GONE); mEndDateHome.setVisibility(View.GONE); } } /** * Removes "Show all timezone" footer and adds all timezones to the dialog. */ private void showAllTimezone(ListView listView) { final ListView lv = listView; // For making this variable available from Runnable. lv.removeFooterView(mTimezoneFooterView); mTimezoneAdapter.showAllTimezones(); final int row = mTimezoneAdapter.getRowById(mTimezone); // we need to post the selection changes to have them have any effect. lv.post(new Runnable() { @Override public void run() { lv.setItemChecked(row, true); lv.setSelection(row); } }); } private void showTimezoneDialog() { mTimezoneAdapter = new TimezoneAdapter(this, mTimezone); final int row = mTimezoneAdapter.getRowById(mTimezone); mTimezoneDialog = new AlertDialog.Builder(this) .setTitle(R.string.timezone_label) .setSingleChoiceItems(mTimezoneAdapter, row, this) .create(); final ListView lv = mTimezoneDialog.getListView(); mTimezoneFooterView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAllTimezone(lv); } }); lv.addFooterView(mTimezoneFooterView); mTimezoneDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && lv.getSelectedView() == mTimezoneFooterView) { showAllTimezone(lv); return true; } else { return false; } } }); mTimezoneDialog.show(); } private void populateRepeats() { Time time = mStartTime; Resources r = getResources(); int resource = android.R.layout.simple_spinner_item; String[] days = new String[] { DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_MEDIUM), DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM), }; String[] ordinals = r.getStringArray(R.array.ordinal_labels); // Only display "Custom" in the spinner if the device does not support the // recurrence functionality of the event. Only display every weekday if // the event starts on a weekday. boolean isCustomRecurrence = isCustomRecurrence(); boolean isWeekdayEvent = isWeekdayEvent(); ArrayList<String> repeatArray = new ArrayList<String>(0); ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0); repeatArray.add(r.getString(R.string.does_not_repeat)); recurrenceIndexes.add(DOES_NOT_REPEAT); repeatArray.add(r.getString(R.string.daily)); recurrenceIndexes.add(REPEATS_DAILY); if (isWeekdayEvent) { repeatArray.add(r.getString(R.string.every_weekday)); recurrenceIndexes.add(REPEATS_EVERY_WEEKDAY); } String format = r.getString(R.string.weekly); repeatArray.add(String.format(format, time.format("%A"))); recurrenceIndexes.add(REPEATS_WEEKLY_ON_DAY); // Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance of the given day. int dayNumber = (time.monthDay - 1) / 7; format = r.getString(R.string.monthly_on_day_count); repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay])); recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY_COUNT); format = r.getString(R.string.monthly_on_day); repeatArray.add(String.format(format, time.monthDay)); recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY); long when = time.toMillis(false); format = r.getString(R.string.yearly); int flags = 0; if (DateFormat.is24HourFormat(this)) { flags |= DateUtils.FORMAT_24HOUR; } repeatArray.add(String.format(format, DateUtils.formatDateTime(this, when, flags))); recurrenceIndexes.add(REPEATS_YEARLY); if (isCustomRecurrence) { repeatArray.add(r.getString(R.string.custom)); recurrenceIndexes.add(REPEATS_CUSTOM); } mRecurrenceIndexes = recurrenceIndexes; int position = recurrenceIndexes.indexOf(DOES_NOT_REPEAT); if (!TextUtils.isEmpty(mRrule)) { if (isCustomRecurrence) { position = recurrenceIndexes.indexOf(REPEATS_CUSTOM); } else { switch (mEventRecurrence.freq) { case EventRecurrence.DAILY: position = recurrenceIndexes.indexOf(REPEATS_DAILY); break; case EventRecurrence.WEEKLY: if (mEventRecurrence.repeatsOnEveryWeekDay()) { position = recurrenceIndexes.indexOf(REPEATS_EVERY_WEEKDAY); } else { position = recurrenceIndexes.indexOf(REPEATS_WEEKLY_ON_DAY); } break; case EventRecurrence.MONTHLY: if (mEventRecurrence.repeatsMonthlyOnDayCount()) { position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY_COUNT); } else { position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY); } break; case EventRecurrence.YEARLY: position = recurrenceIndexes.indexOf(REPEATS_YEARLY); break; } } } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource, repeatArray); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mRepeatsSpinner.setAdapter(adapter); mRepeatsSpinner.setSelection(position); } // Adds a reminder to the displayed list of reminders. // Returns true if successfully added reminder, false if no reminders can // be added. static boolean addReminder(Activity activity, View.OnClickListener listener, ArrayList<LinearLayout> items, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { if (items.size() >= MAX_REMINDERS) { return false; } LayoutInflater inflater = activity.getLayoutInflater(); LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container); LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null); parent.addView(reminderItem); Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value); Resources res = activity.getResources(); spinner.setPrompt(res.getString(R.string.reminders_label)); int resource = android.R.layout.simple_spinner_item; ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); ImageButton reminderRemoveButton; reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove); reminderRemoveButton.setOnClickListener(listener); int index = findMinutesInReminderList(values, minutes); spinner.setSelection(index); items.add(reminderItem); return true; } static void addMinutesToList(Context context, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { int index = values.indexOf(minutes); if (index != -1) { return; } // The requested "minutes" does not exist in the list, so insert it // into the list. String label = constructReminderLabel(context, minutes, false); int len = values.size(); for (int i = 0; i < len; i++) { if (minutes < values.get(i)) { values.add(i, minutes); labels.add(i, label); return; } } values.add(minutes); labels.add(len, label); } /** * Finds the index of the given "minutes" in the "values" list. * * @param values the list of minutes corresponding to the spinner choices * @param minutes the minutes to search for in the values list * @return the index of "minutes" in the "values" list */ private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) { int index = values.indexOf(minutes); if (index == -1) { // This should never happen. Log.e("Cal", "Cannot find minutes (" + minutes + ") in list"); return 0; } return index; } // Constructs a label given an arbitrary number of minutes. For example, // if the given minutes is 63, then this returns the string "63 minutes". // As another example, if the given minutes is 120, then this returns // "2 hours". static String constructReminderLabel(Context context, int minutes, boolean abbrev) { Resources resources = context.getResources(); int value, resId; if (minutes % 60 != 0) { value = minutes; if (abbrev) { resId = R.plurals.Nmins; } else { resId = R.plurals.Nminutes; } } else if (minutes % (24 * 60) != 0) { value = minutes / 60; resId = R.plurals.Nhours; } else { value = minutes / ( 24 * 60); resId = R.plurals.Ndays; } String format = resources.getQuantityString(resId, value); return String.format(format, value); } private void updateRemindersVisibility() { if (mReminderItems.size() == 0) { mRemindersSeparator.setVisibility(View.GONE); mRemindersContainer.setVisibility(View.GONE); } else { mRemindersSeparator.setVisibility(View.VISIBLE); mRemindersContainer.setVisibility(View.VISIBLE); } } private void setDate(TextView view, long millis) { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_WEEKDAY; mSB.setLength(0); String dateString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone) .toString(); view.setText(dateString); } private void setTime(TextView view, long millis) { int flags = DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(this)) { flags |= DateUtils.FORMAT_24HOUR; } mSB.setLength(0); String timeString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone) .toString(); view.setText(timeString); } private void setTimezone(int i) { if (i < 0 || i > mTimezoneAdapter.getCount()) { return; // do nothing } TimezoneRow timezone = mTimezoneAdapter.getItem(i); mTimezoneButton.setText(timezone.toString()); mTimezone = timezone.mId; mTimezoneAdapter.setCurrentTimezone(mTimezone); mStartTime.timezone = mTimezone; mStartTime.normalize(true); mEndTime.timezone = mTimezone; mEndTime.normalize(true); } // Saves the event. Returns true if it is okay to exit this activity. private boolean save() { boolean forceSaveReminders = false; // If we are creating a new event, then make sure we wait until the // query to fetch the list of calendars has finished. if (mEventCursor == null) { if (!mCalendarsQueryComplete) { // Wait for the calendars query to finish. if (mLoadingCalendarsDialog == null) { // Create the progress dialog mLoadingCalendarsDialog = ProgressDialog.show(this, getText(R.string.loading_calendars_title), getText(R.string.loading_calendars_message), true, true, this); mSaveAfterQueryComplete = true; } return false; } // Avoid creating a new event if the calendars cursor is empty or we clicked through // too quickly and no calendar was selected (blame the monkey) if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 || mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) { Log.w("Cal", "The calendars table does not contain any calendars" + " or no calendar was selected." + " New event was not created."); return true; } Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show(); } ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int eventIdIndex = -1; ContentValues values = getContentValuesFromUi(); Uri uri = mUri; // save the timezone as a recent one if (!mAllDayCheckBox.isChecked()) { mTimezoneAdapter.saveRecentTimezone(mTimezone); } // Update the "hasAlarm" field for the event ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); int len = reminderMinutes.size(); values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0); // For recurring events, we must make sure that we use duration rather // than dtend. if (uri == null) { // Add hasAttendeeData for a new event values.put(Events.HAS_ATTENDEE_DATA, 1); // Create new event with new contents addRecurrenceRule(values); if (!TextUtils.isEmpty(mRrule)) { values.remove(Events.DTEND); } eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (TextUtils.isEmpty(mRrule)) { // Modify contents of a non-repeating event addRecurrenceRule(values); checkTimeDependentFields(values); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); - } else if (mInitialValues.getAsString(Events.RRULE) == null) { + } else if (TextUtils.isEmpty(mInitialValues.getAsString(Events.RRULE))) { // This event was changed from a non-repeating event to a // repeating event. addRecurrenceRule(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } else if (mModification == MODIFY_SELECTED) { // Modify contents of the current instance of repeating event // Create a recurrence exception long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME); values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID)); values.put(Events.ORIGINAL_INSTANCE_TIME, begin); boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0; values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0); eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (mModification == MODIFY_ALL_FOLLOWING) { // Modify this instance and all future instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // If the event we are editing is the first in the series, // then delete the whole series. Otherwise, update the series // to end at the new start time. if (isFirstEventInSeries()) { ops.add(ContentProviderOperation.newDelete(uri).build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); } eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); } else { if (isFirstEventInSeries()) { checkTimeDependentFields(values); values.remove(Events.DTEND); Builder b = ContentProviderOperation.newUpdate(uri).withValues(values); ops.add(b.build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); // Create a new event with the user-modified fields values.remove(Events.DTEND); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues( values).build()); } } forceSaveReminders = true; } else if (mModification == MODIFY_ALL) { // Modify all instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // Delete the whole series and replace it with a new // non-recurring event. ops.add(ContentProviderOperation.newDelete(uri).build()); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); forceSaveReminders = true; } else { checkTimeDependentFields(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } } // New Event or New Exception to an existing event boolean newEvent = (eventIdIndex != -1); if (newEvent) { saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes, forceSaveReminders); } else if (uri != null) { long eventId = ContentUris.parseId(uri); saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes, forceSaveReminders); } Builder b; // New event/instance - Set Organizer's response as yes if (mHasAttendeeData && newEvent) { values.clear(); int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition(); // Save the default calendar for new events if (mCalendarsCursor != null) { if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) { String defaultCalendar = mCalendarsCursor .getString(CALENDARS_INDEX_OWNER_ACCOUNT); Utils.setSharedPreference(this, CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar); } } String ownerEmail = mOwnerAccount; // Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor if (ownerEmail == null && mCalendarsCursor != null && mCalendarsCursor.moveToPosition(calendarCursorPosition)) { ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); } if (ownerEmail != null) { values.put(Attendees.ATTENDEE_EMAIL, ownerEmail); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED; // Don't accept for secondary calendars if (ownerEmail.endsWith("calendar.google.com")) { initialStatus = Attendees.ATTENDEE_STATUS_NONE; } values.put(Attendees.ATTENDEE_STATUS, initialStatus); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex); ops.add(b.build()); } } // TODO: is this the right test? this currently checks if this is // a new event or an existing event. or is this a paranoia check? if (mHasAttendeeData && (newEvent || uri != null)) { Editable attendeesText = mAttendeesList.getText(); // Hit the content provider only if this is a new event or the user has changed it if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) { // figure out which attendees need to be added and which ones // need to be deleted. use a linked hash set, so we maintain // order (but also remove duplicates). LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList); // the eventId is only used if eventIdIndex is -1. // TODO: clean up this code. long eventId = uri != null ? ContentUris.parseId(uri) : -1; // only compute deltas if this is an existing event. // new events (being inserted into the Events table) won't // have any existing attendees. if (!newEvent) { HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>(); HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>(); Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees); for (Rfc822Token originalAttendee : originalAttendees) { if (newAttendees.contains(originalAttendee)) { // existing attendee. remove from new attendees set. newAttendees.remove(originalAttendee); } else { // no longer in attendees. mark as removed. removedAttendees.add(originalAttendee); } } // delete removed attendees b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI); String[] args = new String[removedAttendees.size() + 1]; args[0] = Long.toString(eventId); int i = 1; StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX); for (Rfc822Token removedAttendee : removedAttendees) { if (i > 1) { deleteWhere.append(","); } deleteWhere.append("?"); args[i++] = removedAttendee.getAddress(); } deleteWhere.append(")"); b.withSelection(deleteWhere.toString(), args); ops.add(b.build()); } if (newAttendees.size() > 0) { // Insert the new attendees for (Rfc822Token attendee : newAttendees) { values.clear(); values.put(Attendees.ATTENDEE_NAME, attendee.getName()); values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress()); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE); if (newEvent) { b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex); } else { values.put(Attendees.EVENT_ID, eventId); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); } ops.add(b.build()); } } } } try { // TODO Move this to background thread ContentProviderResult[] results = getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops); if (DEBUG) { for (int i = 0; i < results.length; i++) { Log.v(TAG, "results = " + results[i].toString()); } } } catch (RemoteException e) { Log.w(TAG, "Ignoring unexpected remote exception", e); } catch (OperationApplicationException e) { Log.w(TAG, "Ignoring unexpected exception", e); } return true; } private boolean isFirstEventInSeries() { int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART); long start = mEventCursor.getLong(dtStart); return start == mStartTime.toMillis(true); } private void updatePastEvents(ArrayList<ContentProviderOperation> ops, Uri uri) { long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART); String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION); boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE); mEventRecurrence.parse(oldRrule); Time untilTime = new Time(); long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME); ContentValues oldValues = new ContentValues(); // The "until" time must be in UTC time in order for Google calendar // to display it properly. For all-day events, the "until" time string // must include just the date field, and not the time field. The // repeating events repeat up to and including the "until" time. untilTime.timezone = Time.TIMEZONE_UTC; // Subtract one second from the old begin time to get the new // "until" time. untilTime.set(begin - 1000); // subtract one second (1000 millis) if (allDay) { untilTime.hour = 0; untilTime.minute = 0; untilTime.second = 0; untilTime.allDay = true; untilTime.normalize(false); // For all-day events, the duration must be in days, not seconds. // Otherwise, Google Calendar will (mistakenly) change this event // into a non-all-day event. int len = oldDuration.length(); if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') { int seconds = Integer.parseInt(oldDuration.substring(1, len - 1)); int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS; oldDuration = "P" + days + "D"; } } mEventRecurrence.until = untilTime.format2445(); oldValues.put(Events.DTSTART, oldStartMillis); oldValues.put(Events.DURATION, oldDuration); oldValues.put(Events.RRULE, mEventRecurrence.toString()); Builder b = ContentProviderOperation.newUpdate(uri).withValues(oldValues); ops.add(b.build()); } private void checkTimeDependentFields(ContentValues values) { long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME); long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME); boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0; String oldRrule = mInitialValues.getAsString(Events.RRULE); String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE); long newBegin = values.getAsLong(Events.DTSTART); long newEnd = values.getAsLong(Events.DTEND); boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0; String newRrule = values.getAsString(Events.RRULE); String newTimezone = values.getAsString(Events.EVENT_TIMEZONE); // If none of the time-dependent fields changed, then remove them. if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay && TextUtils.equals(oldRrule, newRrule) && TextUtils.equals(oldTimezone, newTimezone)) { values.remove(Events.DTSTART); values.remove(Events.DTEND); values.remove(Events.DURATION); values.remove(Events.ALL_DAY); values.remove(Events.RRULE); values.remove(Events.EVENT_TIMEZONE); return; } if (TextUtils.isEmpty(oldRrule) || TextUtils.isEmpty(newRrule)) { return; } // If we are modifying all events then we need to set DTSTART to the // start time of the first event in the series, not the current // date and time. If the start time of the event was changed // (from, say, 3pm to 4pm), then we want to add the time difference // to the start time of the first event in the series (the DTSTART // value). If we are modifying one instance or all following instances, // then we leave the DTSTART field alone. if (mModification == MODIFY_ALL) { long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART); if (oldBegin != newBegin) { // The user changed the start time of this event long offset = newBegin - oldBegin; oldStartMillis += offset; } values.put(Events.DTSTART, oldStartMillis); } } static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems, ArrayList<Integer> reminderValues) { int len = reminderItems.size(); ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len); for (int index = 0; index < len; index++) { LinearLayout layout = reminderItems.get(index); Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value); int minutes = reminderValues.get(spinner.getSelectedItemPosition()); reminderMinutes.add(minutes); } return reminderMinutes; } /** * Saves the reminders, if they changed. Returns true if the database * was updated. * * @param ops the array of ContentProviderOperations * @param eventId the id of the event whose reminders are being updated * @param reminderMinutes the array of reminders set by the user * @param originalMinutes the original array of reminders * @param forceSave if true, then save the reminders even if they didn't * change * @return true if the database was updated */ static boolean saveReminders(ArrayList<ContentProviderOperation> ops, long eventId, ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes, boolean forceSave) { // If the reminders have not changed, then don't update the database if (reminderMinutes.equals(originalMinutes) && !forceSave) { return false; } // Delete all the existing reminders for this event String where = Reminders.EVENT_ID + "=?"; String[] args = new String[] { Long.toString(eventId) }; Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI); b.withSelection(where, args); ops.add(b.build()); ContentValues values = new ContentValues(); int len = reminderMinutes.size(); // Insert the new reminders, if any for (int i = 0; i < len; i++) { int minutes = reminderMinutes.get(i); values.clear(); values.put(Reminders.MINUTES, minutes); values.put(Reminders.METHOD, Reminders.METHOD_ALERT); values.put(Reminders.EVENT_ID, eventId); b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values); ops.add(b.build()); } return true; } static boolean saveRemindersWithBackRef(ArrayList<ContentProviderOperation> ops, int eventIdIndex, ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes, boolean forceSave) { // If the reminders have not changed, then don't update the database if (reminderMinutes.equals(originalMinutes) && !forceSave) { return false; } // Delete all the existing reminders for this event Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI); b.withSelection(Reminders.EVENT_ID + "=?", new String[1]); b.withSelectionBackReference(0, eventIdIndex); ops.add(b.build()); ContentValues values = new ContentValues(); int len = reminderMinutes.size(); // Insert the new reminders, if any for (int i = 0; i < len; i++) { int minutes = reminderMinutes.get(i); values.clear(); values.put(Reminders.MINUTES, minutes); values.put(Reminders.METHOD, Reminders.METHOD_ALERT); b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values); b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex); ops.add(b.build()); } return true; } private void addRecurrenceRule(ContentValues values) { updateRecurrenceRule(); if (TextUtils.isEmpty(mRrule)) { return; } values.put(Events.RRULE, mRrule); long end = mEndTime.toMillis(true /* ignore dst */); long start = mStartTime.toMillis(true /* ignore dst */); String duration; boolean isAllDay = mAllDayCheckBox.isChecked(); if (isAllDay) { long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS; duration = "P" + days + "D"; } else { long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS; duration = "P" + seconds + "S"; } values.put(Events.DURATION, duration); } private void clearRecurrence() { mEventRecurrence.byday = null; mEventRecurrence.bydayNum = null; mEventRecurrence.bydayCount = 0; mEventRecurrence.bymonth = null; mEventRecurrence.bymonthCount = 0; mEventRecurrence.bymonthday = null; mEventRecurrence.bymonthdayCount = 0; } private void updateRecurrenceRule() { int position = mRepeatsSpinner.getSelectedItemPosition(); int selection = mRecurrenceIndexes.get(position); // Make sure we don't have any leftover data from the previous setting clearRecurrence(); if (selection == DOES_NOT_REPEAT) { mRrule = null; return; } else if (selection == REPEATS_CUSTOM) { // Keep custom recurrence as before. return; } else if (selection == REPEATS_DAILY) { mEventRecurrence.freq = EventRecurrence.DAILY; } else if (selection == REPEATS_EVERY_WEEKDAY) { mEventRecurrence.freq = EventRecurrence.WEEKLY; int dayCount = 5; int[] byday = new int[dayCount]; int[] bydayNum = new int[dayCount]; byday[0] = EventRecurrence.MO; byday[1] = EventRecurrence.TU; byday[2] = EventRecurrence.WE; byday[3] = EventRecurrence.TH; byday[4] = EventRecurrence.FR; for (int day = 0; day < dayCount; day++) { bydayNum[day] = 0; } mEventRecurrence.byday = byday; mEventRecurrence.bydayNum = bydayNum; mEventRecurrence.bydayCount = dayCount; } else if (selection == REPEATS_WEEKLY_ON_DAY) { mEventRecurrence.freq = EventRecurrence.WEEKLY; int[] days = new int[1]; int dayCount = 1; int[] dayNum = new int[dayCount]; days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay); // not sure why this needs to be zero, but set it for now. dayNum[0] = 0; mEventRecurrence.byday = days; mEventRecurrence.bydayNum = dayNum; mEventRecurrence.bydayCount = dayCount; } else if (selection == REPEATS_MONTHLY_ON_DAY) { mEventRecurrence.freq = EventRecurrence.MONTHLY; mEventRecurrence.bydayCount = 0; mEventRecurrence.bymonthdayCount = 1; int[] bymonthday = new int[1]; bymonthday[0] = mStartTime.monthDay; mEventRecurrence.bymonthday = bymonthday; } else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) { mEventRecurrence.freq = EventRecurrence.MONTHLY; mEventRecurrence.bydayCount = 1; mEventRecurrence.bymonthdayCount = 0; int[] byday = new int[1]; int[] bydayNum = new int[1]; // Compute the week number (for example, the "2nd" Monday) int dayCount = 1 + ((mStartTime.monthDay - 1) / 7); if (dayCount == 5) { dayCount = -1; } bydayNum[0] = dayCount; byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay); mEventRecurrence.byday = byday; mEventRecurrence.bydayNum = bydayNum; } else if (selection == REPEATS_YEARLY) { mEventRecurrence.freq = EventRecurrence.YEARLY; } // Set the week start day. mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek); mRrule = mEventRecurrence.toString(); } private ContentValues getContentValuesFromUi() { String title = mTitleTextView.getText().toString().trim(); boolean isAllDay = mAllDayCheckBox.isChecked(); String location = mLocationTextView.getText().toString().trim(); String description = mDescriptionTextView.getText().toString().trim(); ContentValues values = new ContentValues(); long startMillis; long endMillis; long calendarId; if (isAllDay) { // Reset start and end time, increment the monthDay by 1, and set // the timezone to UTC, as required for all-day events. mTimezone = Time.TIMEZONE_UTC; mStartTime.hour = 0; mStartTime.minute = 0; mStartTime.second = 0; mStartTime.timezone = mTimezone; startMillis = mStartTime.normalize(true); mEndTime.hour = 0; mEndTime.minute = 0; mEndTime.second = 0; mEndTime.monthDay++; mEndTime.timezone = mTimezone; endMillis = mEndTime.normalize(true); if (mEventCursor == null) { // This is a new event calendarId = mCalendarsSpinner.getSelectedItemId(); } else { calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID); } } else { if (mEventCursor != null) { calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID); } else { // This is a new event calendarId = mCalendarsSpinner.getSelectedItemId(); } // mTimezone is set automatically in onClick mStartTime.timezone = mTimezone; mEndTime.timezone = mTimezone; startMillis = mStartTime.toMillis(true); endMillis = mEndTime.toMillis(true); } values.put(Events.CALENDAR_ID, calendarId); values.put(Events.EVENT_TIMEZONE, mTimezone); values.put(Events.TITLE, title); values.put(Events.ALL_DAY, isAllDay ? 1 : 0); values.put(Events.DTSTART, startMillis); values.put(Events.DTEND, endMillis); values.put(Events.DESCRIPTION, description); values.put(Events.EVENT_LOCATION, location); values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition()); int visibility = mVisibilitySpinner.getSelectedItemPosition(); if (visibility > 0) { // For now we the array contains the values 0, 2, and 3. We add one to match. visibility++; } values.put(Events.VISIBILITY, visibility); return values; } private boolean isEmpty() { String title = mTitleTextView.getText().toString().trim(); if (title.length() > 0) { return false; } String location = mLocationTextView.getText().toString().trim(); if (location.length() > 0) { return false; } String description = mDescriptionTextView.getText().toString().trim(); if (description.length() > 0) { return false; } return true; } private boolean isCustomRecurrence() { if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) { return true; } if (mEventRecurrence.freq == 0) { return false; } switch (mEventRecurrence.freq) { case EventRecurrence.DAILY: return false; case EventRecurrence.WEEKLY: if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) { return false; } else if (mEventRecurrence.bydayCount == 1) { return false; } break; case EventRecurrence.MONTHLY: if (mEventRecurrence.repeatsMonthlyOnDayCount()) { return false; } else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) { return false; } break; case EventRecurrence.YEARLY: return false; } return true; } private boolean isWeekdayEvent() { if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) { return true; } return false; } }
true
true
private boolean save() { boolean forceSaveReminders = false; // If we are creating a new event, then make sure we wait until the // query to fetch the list of calendars has finished. if (mEventCursor == null) { if (!mCalendarsQueryComplete) { // Wait for the calendars query to finish. if (mLoadingCalendarsDialog == null) { // Create the progress dialog mLoadingCalendarsDialog = ProgressDialog.show(this, getText(R.string.loading_calendars_title), getText(R.string.loading_calendars_message), true, true, this); mSaveAfterQueryComplete = true; } return false; } // Avoid creating a new event if the calendars cursor is empty or we clicked through // too quickly and no calendar was selected (blame the monkey) if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 || mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) { Log.w("Cal", "The calendars table does not contain any calendars" + " or no calendar was selected." + " New event was not created."); return true; } Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show(); } ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int eventIdIndex = -1; ContentValues values = getContentValuesFromUi(); Uri uri = mUri; // save the timezone as a recent one if (!mAllDayCheckBox.isChecked()) { mTimezoneAdapter.saveRecentTimezone(mTimezone); } // Update the "hasAlarm" field for the event ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); int len = reminderMinutes.size(); values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0); // For recurring events, we must make sure that we use duration rather // than dtend. if (uri == null) { // Add hasAttendeeData for a new event values.put(Events.HAS_ATTENDEE_DATA, 1); // Create new event with new contents addRecurrenceRule(values); if (!TextUtils.isEmpty(mRrule)) { values.remove(Events.DTEND); } eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (TextUtils.isEmpty(mRrule)) { // Modify contents of a non-repeating event addRecurrenceRule(values); checkTimeDependentFields(values); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } else if (mInitialValues.getAsString(Events.RRULE) == null) { // This event was changed from a non-repeating event to a // repeating event. addRecurrenceRule(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } else if (mModification == MODIFY_SELECTED) { // Modify contents of the current instance of repeating event // Create a recurrence exception long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME); values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID)); values.put(Events.ORIGINAL_INSTANCE_TIME, begin); boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0; values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0); eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (mModification == MODIFY_ALL_FOLLOWING) { // Modify this instance and all future instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // If the event we are editing is the first in the series, // then delete the whole series. Otherwise, update the series // to end at the new start time. if (isFirstEventInSeries()) { ops.add(ContentProviderOperation.newDelete(uri).build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); } eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); } else { if (isFirstEventInSeries()) { checkTimeDependentFields(values); values.remove(Events.DTEND); Builder b = ContentProviderOperation.newUpdate(uri).withValues(values); ops.add(b.build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); // Create a new event with the user-modified fields values.remove(Events.DTEND); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues( values).build()); } } forceSaveReminders = true; } else if (mModification == MODIFY_ALL) { // Modify all instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // Delete the whole series and replace it with a new // non-recurring event. ops.add(ContentProviderOperation.newDelete(uri).build()); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); forceSaveReminders = true; } else { checkTimeDependentFields(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } } // New Event or New Exception to an existing event boolean newEvent = (eventIdIndex != -1); if (newEvent) { saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes, forceSaveReminders); } else if (uri != null) { long eventId = ContentUris.parseId(uri); saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes, forceSaveReminders); } Builder b; // New event/instance - Set Organizer's response as yes if (mHasAttendeeData && newEvent) { values.clear(); int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition(); // Save the default calendar for new events if (mCalendarsCursor != null) { if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) { String defaultCalendar = mCalendarsCursor .getString(CALENDARS_INDEX_OWNER_ACCOUNT); Utils.setSharedPreference(this, CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar); } } String ownerEmail = mOwnerAccount; // Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor if (ownerEmail == null && mCalendarsCursor != null && mCalendarsCursor.moveToPosition(calendarCursorPosition)) { ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); } if (ownerEmail != null) { values.put(Attendees.ATTENDEE_EMAIL, ownerEmail); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED; // Don't accept for secondary calendars if (ownerEmail.endsWith("calendar.google.com")) { initialStatus = Attendees.ATTENDEE_STATUS_NONE; } values.put(Attendees.ATTENDEE_STATUS, initialStatus); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex); ops.add(b.build()); } } // TODO: is this the right test? this currently checks if this is // a new event or an existing event. or is this a paranoia check? if (mHasAttendeeData && (newEvent || uri != null)) { Editable attendeesText = mAttendeesList.getText(); // Hit the content provider only if this is a new event or the user has changed it if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) { // figure out which attendees need to be added and which ones // need to be deleted. use a linked hash set, so we maintain // order (but also remove duplicates). LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList); // the eventId is only used if eventIdIndex is -1. // TODO: clean up this code. long eventId = uri != null ? ContentUris.parseId(uri) : -1; // only compute deltas if this is an existing event. // new events (being inserted into the Events table) won't // have any existing attendees. if (!newEvent) { HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>(); HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>(); Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees); for (Rfc822Token originalAttendee : originalAttendees) { if (newAttendees.contains(originalAttendee)) { // existing attendee. remove from new attendees set. newAttendees.remove(originalAttendee); } else { // no longer in attendees. mark as removed. removedAttendees.add(originalAttendee); } } // delete removed attendees b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI); String[] args = new String[removedAttendees.size() + 1]; args[0] = Long.toString(eventId); int i = 1; StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX); for (Rfc822Token removedAttendee : removedAttendees) { if (i > 1) { deleteWhere.append(","); } deleteWhere.append("?"); args[i++] = removedAttendee.getAddress(); } deleteWhere.append(")"); b.withSelection(deleteWhere.toString(), args); ops.add(b.build()); } if (newAttendees.size() > 0) { // Insert the new attendees for (Rfc822Token attendee : newAttendees) { values.clear(); values.put(Attendees.ATTENDEE_NAME, attendee.getName()); values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress()); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE); if (newEvent) { b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex); } else { values.put(Attendees.EVENT_ID, eventId); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); } ops.add(b.build()); } } } } try { // TODO Move this to background thread ContentProviderResult[] results = getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops); if (DEBUG) { for (int i = 0; i < results.length; i++) { Log.v(TAG, "results = " + results[i].toString()); } } } catch (RemoteException e) { Log.w(TAG, "Ignoring unexpected remote exception", e); } catch (OperationApplicationException e) { Log.w(TAG, "Ignoring unexpected exception", e); } return true; }
private boolean save() { boolean forceSaveReminders = false; // If we are creating a new event, then make sure we wait until the // query to fetch the list of calendars has finished. if (mEventCursor == null) { if (!mCalendarsQueryComplete) { // Wait for the calendars query to finish. if (mLoadingCalendarsDialog == null) { // Create the progress dialog mLoadingCalendarsDialog = ProgressDialog.show(this, getText(R.string.loading_calendars_title), getText(R.string.loading_calendars_message), true, true, this); mSaveAfterQueryComplete = true; } return false; } // Avoid creating a new event if the calendars cursor is empty or we clicked through // too quickly and no calendar was selected (blame the monkey) if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 || mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) { Log.w("Cal", "The calendars table does not contain any calendars" + " or no calendar was selected." + " New event was not created."); return true; } Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show(); } ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int eventIdIndex = -1; ContentValues values = getContentValuesFromUi(); Uri uri = mUri; // save the timezone as a recent one if (!mAllDayCheckBox.isChecked()) { mTimezoneAdapter.saveRecentTimezone(mTimezone); } // Update the "hasAlarm" field for the event ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); int len = reminderMinutes.size(); values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0); // For recurring events, we must make sure that we use duration rather // than dtend. if (uri == null) { // Add hasAttendeeData for a new event values.put(Events.HAS_ATTENDEE_DATA, 1); // Create new event with new contents addRecurrenceRule(values); if (!TextUtils.isEmpty(mRrule)) { values.remove(Events.DTEND); } eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (TextUtils.isEmpty(mRrule)) { // Modify contents of a non-repeating event addRecurrenceRule(values); checkTimeDependentFields(values); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } else if (TextUtils.isEmpty(mInitialValues.getAsString(Events.RRULE))) { // This event was changed from a non-repeating event to a // repeating event. addRecurrenceRule(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } else if (mModification == MODIFY_SELECTED) { // Modify contents of the current instance of repeating event // Create a recurrence exception long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME); values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID)); values.put(Events.ORIGINAL_INSTANCE_TIME, begin); boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0; values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0); eventIdIndex = ops.size(); Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values); ops.add(b.build()); forceSaveReminders = true; } else if (mModification == MODIFY_ALL_FOLLOWING) { // Modify this instance and all future instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // If the event we are editing is the first in the series, // then delete the whole series. Otherwise, update the series // to end at the new start time. if (isFirstEventInSeries()) { ops.add(ContentProviderOperation.newDelete(uri).build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); } eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); } else { if (isFirstEventInSeries()) { checkTimeDependentFields(values); values.remove(Events.DTEND); Builder b = ContentProviderOperation.newUpdate(uri).withValues(values); ops.add(b.build()); } else { // Update the current repeating event to end at the new // start time. updatePastEvents(ops, uri); // Create a new event with the user-modified fields values.remove(Events.DTEND); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues( values).build()); } } forceSaveReminders = true; } else if (mModification == MODIFY_ALL) { // Modify all instances of repeating event addRecurrenceRule(values); if (TextUtils.isEmpty(mRrule)) { // We've changed a recurring event to a non-recurring event. // Delete the whole series and replace it with a new // non-recurring event. ops.add(ContentProviderOperation.newDelete(uri).build()); eventIdIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values) .build()); forceSaveReminders = true; } else { checkTimeDependentFields(values); values.remove(Events.DTEND); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); } } // New Event or New Exception to an existing event boolean newEvent = (eventIdIndex != -1); if (newEvent) { saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes, forceSaveReminders); } else if (uri != null) { long eventId = ContentUris.parseId(uri); saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes, forceSaveReminders); } Builder b; // New event/instance - Set Organizer's response as yes if (mHasAttendeeData && newEvent) { values.clear(); int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition(); // Save the default calendar for new events if (mCalendarsCursor != null) { if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) { String defaultCalendar = mCalendarsCursor .getString(CALENDARS_INDEX_OWNER_ACCOUNT); Utils.setSharedPreference(this, CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar); } } String ownerEmail = mOwnerAccount; // Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor if (ownerEmail == null && mCalendarsCursor != null && mCalendarsCursor.moveToPosition(calendarCursorPosition)) { ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); } if (ownerEmail != null) { values.put(Attendees.ATTENDEE_EMAIL, ownerEmail); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED; // Don't accept for secondary calendars if (ownerEmail.endsWith("calendar.google.com")) { initialStatus = Attendees.ATTENDEE_STATUS_NONE; } values.put(Attendees.ATTENDEE_STATUS, initialStatus); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex); ops.add(b.build()); } } // TODO: is this the right test? this currently checks if this is // a new event or an existing event. or is this a paranoia check? if (mHasAttendeeData && (newEvent || uri != null)) { Editable attendeesText = mAttendeesList.getText(); // Hit the content provider only if this is a new event or the user has changed it if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) { // figure out which attendees need to be added and which ones // need to be deleted. use a linked hash set, so we maintain // order (but also remove duplicates). LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList); // the eventId is only used if eventIdIndex is -1. // TODO: clean up this code. long eventId = uri != null ? ContentUris.parseId(uri) : -1; // only compute deltas if this is an existing event. // new events (being inserted into the Events table) won't // have any existing attendees. if (!newEvent) { HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>(); HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>(); Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees); for (Rfc822Token originalAttendee : originalAttendees) { if (newAttendees.contains(originalAttendee)) { // existing attendee. remove from new attendees set. newAttendees.remove(originalAttendee); } else { // no longer in attendees. mark as removed. removedAttendees.add(originalAttendee); } } // delete removed attendees b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI); String[] args = new String[removedAttendees.size() + 1]; args[0] = Long.toString(eventId); int i = 1; StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX); for (Rfc822Token removedAttendee : removedAttendees) { if (i > 1) { deleteWhere.append(","); } deleteWhere.append("?"); args[i++] = removedAttendee.getAddress(); } deleteWhere.append(")"); b.withSelection(deleteWhere.toString(), args); ops.add(b.build()); } if (newAttendees.size() > 0) { // Insert the new attendees for (Rfc822Token attendee : newAttendees) { values.clear(); values.put(Attendees.ATTENDEE_NAME, attendee.getName()); values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress()); values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE); values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE); if (newEvent) { b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex); } else { values.put(Attendees.EVENT_ID, eventId); b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI) .withValues(values); } ops.add(b.build()); } } } } try { // TODO Move this to background thread ContentProviderResult[] results = getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops); if (DEBUG) { for (int i = 0; i < results.length; i++) { Log.v(TAG, "results = " + results[i].toString()); } } } catch (RemoteException e) { Log.w(TAG, "Ignoring unexpected remote exception", e); } catch (OperationApplicationException e) { Log.w(TAG, "Ignoring unexpected exception", e); } return true; }
diff --git a/src/UI/ClerkDialog.java b/src/UI/ClerkDialog.java index b97c33f..0239fea 100644 --- a/src/UI/ClerkDialog.java +++ b/src/UI/ClerkDialog.java @@ -1,114 +1,114 @@ package UI; import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class ClerkDialog extends JFrame implements ActionListener{ static JFrame mainFrame; static String addBorrowerCommand = "addBorrowerPressed"; static String checkOutItemsCommand = "checkOutItemsPressed"; static String processReturnCommand = "processReturnPressed"; static String checkOverdueCommand = "overduePressed"; static String returnToChooseUserDialogCommand = "Return to User Dialog"; JTextField returnField = new JTextField(); public ClerkDialog(String name) { super (name); } private void addComponentsToPane(final Container pane) { JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(3, 3)); + panel.setLayout(new GridLayout(2, 3)); JButton addBorrowerButton = new JButton("Add Borrower"); addBorrowerButton.setVerticalTextPosition(AbstractButton.CENTER); addBorrowerButton.setHorizontalTextPosition(AbstractButton.CENTER); addBorrowerButton.setActionCommand(addBorrowerCommand); addBorrowerButton.addActionListener(this); JButton checkOutItems = new JButton("Check Out Items"); checkOutItems.setVerticalTextPosition(AbstractButton.CENTER); checkOutItems.setHorizontalTextPosition(AbstractButton.CENTER); checkOutItems.setActionCommand(checkOutItemsCommand); checkOutItems.addActionListener(this); JButton overdueButton = new JButton ("Check Overdues"); overdueButton.setVerticalAlignment(AbstractButton.CENTER); overdueButton.setHorizontalAlignment(AbstractButton.CENTER); overdueButton.setActionCommand(checkOverdueCommand); overdueButton.addActionListener(this); panel.add(addBorrowerButton); panel.add(checkOutItems); panel.add(overdueButton); JButton processReturn = new JButton ("Process Return"); processReturn.setVerticalAlignment(AbstractButton.CENTER); processReturn.setHorizontalAlignment(AbstractButton.CENTER); processReturn.setActionCommand(processReturnCommand); processReturn.addActionListener(this); panel.add(new Label("Enter call number to process return")); panel.add(returnField); panel.add(processReturn); JButton backButton = new JButton ("Return to Choose User Dialog"); backButton.setVerticalAlignment(AbstractButton.CENTER); backButton.setHorizontalAlignment(AbstractButton.CENTER); backButton.setActionCommand(processReturnCommand); backButton.addActionListener(this); pane.add(panel); } public static void createAndShowGUI() { //Create and set up the window. ClerkDialog frame = new ClerkDialog("Clerk Dialog"); // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. frame.addComponentsToPane(frame.getContentPane()); //Display the window. frame.pack(); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { if (ClerkDialog.addBorrowerCommand.equals(arg0.getActionCommand())) { //this.setEnabled(false); AddBorrowerDialog.createAndShowGUI(); }else if (ClerkDialog.checkOutItemsCommand.equals(arg0.getActionCommand())) { CheckOutItemsDialog.createAndShowGUI(); }else if (ClerkDialog.processReturnCommand.equals(arg0.getActionCommand())) { //TODO do something with returnField.getText(); //returnField.setText(""); ProcessReturnsDialog.createAndShowGUI(); }else if (ClerkDialog.checkOverdueCommand.equals(arg0.getActionCommand())) { CheckOverduesDialog.createAndShowGUI(); } } }
true
true
private void addComponentsToPane(final Container pane) { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 3)); JButton addBorrowerButton = new JButton("Add Borrower"); addBorrowerButton.setVerticalTextPosition(AbstractButton.CENTER); addBorrowerButton.setHorizontalTextPosition(AbstractButton.CENTER); addBorrowerButton.setActionCommand(addBorrowerCommand); addBorrowerButton.addActionListener(this); JButton checkOutItems = new JButton("Check Out Items"); checkOutItems.setVerticalTextPosition(AbstractButton.CENTER); checkOutItems.setHorizontalTextPosition(AbstractButton.CENTER); checkOutItems.setActionCommand(checkOutItemsCommand); checkOutItems.addActionListener(this); JButton overdueButton = new JButton ("Check Overdues"); overdueButton.setVerticalAlignment(AbstractButton.CENTER); overdueButton.setHorizontalAlignment(AbstractButton.CENTER); overdueButton.setActionCommand(checkOverdueCommand); overdueButton.addActionListener(this); panel.add(addBorrowerButton); panel.add(checkOutItems); panel.add(overdueButton); JButton processReturn = new JButton ("Process Return"); processReturn.setVerticalAlignment(AbstractButton.CENTER); processReturn.setHorizontalAlignment(AbstractButton.CENTER); processReturn.setActionCommand(processReturnCommand); processReturn.addActionListener(this); panel.add(new Label("Enter call number to process return")); panel.add(returnField); panel.add(processReturn); JButton backButton = new JButton ("Return to Choose User Dialog"); backButton.setVerticalAlignment(AbstractButton.CENTER); backButton.setHorizontalAlignment(AbstractButton.CENTER); backButton.setActionCommand(processReturnCommand); backButton.addActionListener(this); pane.add(panel); }
private void addComponentsToPane(final Container pane) { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2, 3)); JButton addBorrowerButton = new JButton("Add Borrower"); addBorrowerButton.setVerticalTextPosition(AbstractButton.CENTER); addBorrowerButton.setHorizontalTextPosition(AbstractButton.CENTER); addBorrowerButton.setActionCommand(addBorrowerCommand); addBorrowerButton.addActionListener(this); JButton checkOutItems = new JButton("Check Out Items"); checkOutItems.setVerticalTextPosition(AbstractButton.CENTER); checkOutItems.setHorizontalTextPosition(AbstractButton.CENTER); checkOutItems.setActionCommand(checkOutItemsCommand); checkOutItems.addActionListener(this); JButton overdueButton = new JButton ("Check Overdues"); overdueButton.setVerticalAlignment(AbstractButton.CENTER); overdueButton.setHorizontalAlignment(AbstractButton.CENTER); overdueButton.setActionCommand(checkOverdueCommand); overdueButton.addActionListener(this); panel.add(addBorrowerButton); panel.add(checkOutItems); panel.add(overdueButton); JButton processReturn = new JButton ("Process Return"); processReturn.setVerticalAlignment(AbstractButton.CENTER); processReturn.setHorizontalAlignment(AbstractButton.CENTER); processReturn.setActionCommand(processReturnCommand); processReturn.addActionListener(this); panel.add(new Label("Enter call number to process return")); panel.add(returnField); panel.add(processReturn); JButton backButton = new JButton ("Return to Choose User Dialog"); backButton.setVerticalAlignment(AbstractButton.CENTER); backButton.setHorizontalAlignment(AbstractButton.CENTER); backButton.setActionCommand(processReturnCommand); backButton.addActionListener(this); pane.add(panel); }
diff --git a/src/Views/TextWindow.java b/src/Views/TextWindow.java index 8e2b2d1..01bf503 100644 --- a/src/Views/TextWindow.java +++ b/src/Views/TextWindow.java @@ -1,56 +1,56 @@ /** * @author:Alex Bogart, Justin Peterson * TextWindow.java represents the actual Swing window that will be kept in the * main focus of the HTML editor. * */ package Views; import Tag.TagCollection; import Views.TextTabWindow; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.ScrollPaneConstants; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; public class TextWindow extends JTextArea{ private static final long serialVersionUID = 1L; /** * Constructs an individual window to add to the TextTabWindow. * @param tabWindow - the main TextTabWindow of the editor. */ public TextWindow(String windowName, TextTabWindow tabWindow, TagCollection tabs){ setLayout(new BorderLayout(5,10)); new JTextArea(); //allows line wrapping; defaults to by letter if wrapStyleWord is false setLineWrap(true); //will not work if lineWrap is false, true wraps by word setWrapStyleWord(true); //change the tab size; default is 8 setTabSize(8); //opens the right-click menu addMouseListener(new RightClickMenu(this, tabs)); //places text area inside a scrolling pane JScrollPane scrollPane = new JScrollPane(this); scrollPane.setBounds(10,60,780,500); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); - tabWindow.addTab(windowName, this); + tabWindow.addTab(windowName, scrollPane); setVisible(true); } }
true
true
public TextWindow(String windowName, TextTabWindow tabWindow, TagCollection tabs){ setLayout(new BorderLayout(5,10)); new JTextArea(); //allows line wrapping; defaults to by letter if wrapStyleWord is false setLineWrap(true); //will not work if lineWrap is false, true wraps by word setWrapStyleWord(true); //change the tab size; default is 8 setTabSize(8); //opens the right-click menu addMouseListener(new RightClickMenu(this, tabs)); //places text area inside a scrolling pane JScrollPane scrollPane = new JScrollPane(this); scrollPane.setBounds(10,60,780,500); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); tabWindow.addTab(windowName, this); setVisible(true); }
public TextWindow(String windowName, TextTabWindow tabWindow, TagCollection tabs){ setLayout(new BorderLayout(5,10)); new JTextArea(); //allows line wrapping; defaults to by letter if wrapStyleWord is false setLineWrap(true); //will not work if lineWrap is false, true wraps by word setWrapStyleWord(true); //change the tab size; default is 8 setTabSize(8); //opens the right-click menu addMouseListener(new RightClickMenu(this, tabs)); //places text area inside a scrolling pane JScrollPane scrollPane = new JScrollPane(this); scrollPane.setBounds(10,60,780,500); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); tabWindow.addTab(windowName, scrollPane); setVisible(true); }
diff --git a/src/com/haubey/tangent/MainActivity.java b/src/com/haubey/tangent/MainActivity.java index 684ea50..8221b2c 100755 --- a/src/com/haubey/tangent/MainActivity.java +++ b/src/com/haubey/tangent/MainActivity.java @@ -1,171 +1,171 @@ package com.haubey.tangent; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import de.congrace.exp4j.Calculable; import de.congrace.exp4j.ExpressionBuilder; import de.congrace.exp4j.UnknownFunctionException; import de.congrace.exp4j.UnparsableExpressionException; public class MainActivity extends FragmentActivity { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Create the adapter that will return a fragment for each of the three primary sections // of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.activity_main, menu); return false; } public void acceptFunction(View view) { EditText functionTextBox = (EditText) findViewById(R.id.function_textbox); String functionString = functionTextBox.getText().toString(); if (functionString.trim().equals("")) { Toast.makeText(getApplicationContext(), "Please Enter A Function", Toast.LENGTH_LONG).show(); return; } if (functionString.contains("e^x")) { - functionString = functionString.replace("e^x", "exp(x)"); + functionString = functionString.replace("e^", "exp("); Toast.makeText(getApplicationContext(), "Replacing e^x", Toast.LENGTH_LONG).show(); } try { Calculable exp = new ExpressionBuilder(functionString).withVariable("x", 10).build(); exp.calculate(); String function = functionString; startActivity(new Intent(this, Grapher.class).putExtra("function", function)); } catch(UnparsableExpressionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } catch(UnknownFunctionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment = null; switch (i) { case 0: fragment = new PreBuiltFunctionList(); break; case 1: fragment = new EnterFunction(); break; case 2: fragment = new DummySectionFragment(); break; } Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1); fragment.setArguments(args); return fragment; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(); case 1: return getString(R.string.title_section2).toUpperCase(); case 2: return getString(R.string.title_section3).toUpperCase(); } return null; } } /** * A dummy fragment representing a section of the app, but that simply displays dummy text. */ public static class DummySectionFragment extends Fragment { public DummySectionFragment() { } public static final String ARG_SECTION_NUMBER = "section_number"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button button = new Button(getActivity()); button.setGravity(Gravity.CENTER); button.setText("Orientation Test"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), OrientationTest.class)); } }); return button; } } }
true
true
public void acceptFunction(View view) { EditText functionTextBox = (EditText) findViewById(R.id.function_textbox); String functionString = functionTextBox.getText().toString(); if (functionString.trim().equals("")) { Toast.makeText(getApplicationContext(), "Please Enter A Function", Toast.LENGTH_LONG).show(); return; } if (functionString.contains("e^x")) { functionString = functionString.replace("e^x", "exp(x)"); Toast.makeText(getApplicationContext(), "Replacing e^x", Toast.LENGTH_LONG).show(); } try { Calculable exp = new ExpressionBuilder(functionString).withVariable("x", 10).build(); exp.calculate(); String function = functionString; startActivity(new Intent(this, Grapher.class).putExtra("function", function)); } catch(UnparsableExpressionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } catch(UnknownFunctionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } }
public void acceptFunction(View view) { EditText functionTextBox = (EditText) findViewById(R.id.function_textbox); String functionString = functionTextBox.getText().toString(); if (functionString.trim().equals("")) { Toast.makeText(getApplicationContext(), "Please Enter A Function", Toast.LENGTH_LONG).show(); return; } if (functionString.contains("e^x")) { functionString = functionString.replace("e^", "exp("); Toast.makeText(getApplicationContext(), "Replacing e^x", Toast.LENGTH_LONG).show(); } try { Calculable exp = new ExpressionBuilder(functionString).withVariable("x", 10).build(); exp.calculate(); String function = functionString; startActivity(new Intent(this, Grapher.class).putExtra("function", function)); } catch(UnparsableExpressionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } catch(UnknownFunctionException e) { Toast.makeText(getApplicationContext(), "Invalid Function, try again", Toast.LENGTH_SHORT).show(); } }
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/sort/ParallelMergeSorter.java b/araqne-logdb/src/main/java/org/araqne/logdb/sort/ParallelMergeSorter.java index 7516a239..79fd9a48 100644 --- a/araqne-logdb/src/main/java/org/araqne/logdb/sort/ParallelMergeSorter.java +++ b/araqne-logdb/src/main/java/org/araqne/logdb/sort/ParallelMergeSorter.java @@ -1,470 +1,473 @@ /* * Copyright 2012 Future Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.araqne.logdb.sort; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ParallelMergeSorter { private static final int DEFAULT_CACHE_SIZE = 10000; private static final int DEFAULT_RUN_LENGTH = 20000; private final Logger logger = LoggerFactory.getLogger(ParallelMergeSorter.class); private Queue<Run> runs = new LinkedBlockingDeque<Run>(); private Queue<PartitionMergeTask> merges = new LinkedBlockingQueue<PartitionMergeTask>(); private LinkedList<Item> buffer; private Comparator<Item> comparator; private int runLength = 20000; private AtomicInteger runIndexer; private volatile int flushTaskCount; private AtomicInteger cacheCount; private Object flushDoneSignal = new Object(); private ExecutorService executor; private CountDownLatch mergeLatch; public ParallelMergeSorter(Comparator<Item> comparator) { this(comparator, DEFAULT_RUN_LENGTH, DEFAULT_CACHE_SIZE); } public ParallelMergeSorter(Comparator<Item> comparator, int runLength) { this(comparator, runLength, DEFAULT_CACHE_SIZE); } public ParallelMergeSorter(Comparator<Item> comparator, int runLength, int memoryRunCount) { this.runLength = runLength; this.comparator = comparator; this.buffer = new LinkedList<Item>(); this.runIndexer = new AtomicInteger(); this.executor = new ThreadPoolExecutor(8, 8, 10, TimeUnit.SECONDS, new LimitedQueue<Runnable>(8)); this.cacheCount = new AtomicInteger(memoryRunCount); } public class LimitedQueue<E> extends ArrayBlockingQueue<E> { private static final long serialVersionUID = 1L; public LimitedQueue(int maxSize) { super(maxSize); } @Override public boolean offer(E e) { // turn offer() and add() into a blocking calls (unless interrupted) try { put(e); return true; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } return false; } } public void add(Item item) throws IOException { buffer.add(item); if (buffer.size() >= runLength) flushRun(); } public void addAll(List<? extends Item> items) throws IOException { buffer.addAll(items); if (buffer.size() >= runLength) flushRun(); } private void flushRun() throws IOException, FileNotFoundException { LinkedList<Item> buffered = buffer; if (buffered.isEmpty()) return; buffer = new LinkedList<Item>(); synchronized (flushDoneSignal) { flushTaskCount++; } executor.submit(new FlushWorker(buffered)); } public CloseableIterator sort() throws IOException { // flush rest objects flushRun(); buffer = null; logger.trace("flush finished."); // wait flush done while (true) { synchronized (flushDoneSignal) { if (flushTaskCount == 0) break; try { flushDoneSignal.wait(); } catch (InterruptedException e) { } logger.debug("araqne logdb: remaining runs {}, task count: {}", runs.size(), flushTaskCount); } } // partition logger.trace("araqne logdb: start partitioning"); long begin = new Date().getTime(); Partitioner partitioner = new Partitioner(comparator); List<SortedRun> sortedRuns = new LinkedList<SortedRun>(); for (Run run : runs) sortedRuns.add(new SortedRunImpl(run)); runs.clear(); int partitionCount = getProperPartitionCount(); List<Partition> partitions = partitioner.partition(partitionCount, sortedRuns); for (SortedRun r : sortedRuns) ((SortedRunImpl) r).close(); long elapsed = new Date().getTime() - begin; logger.trace("araqne logdb: [{}] partitioning completed in {}ms", partitionCount, elapsed); // n-way merge Run run = mergeAll(partitions); executor.shutdown(); logger.trace("merge ended"); if (run.cached != null) return new CacheRunIterator(run.cached.iterator()); else return new FileRunIterator(run.dataFile); } private static int getProperPartitionCount() { int processors = Runtime.getRuntime().availableProcessors(); int count = 2; while (count < processors) count <<= 1; return count; } private static class SortedRunImpl implements SortedRun { private RunInputRandomAccess ra; private Run run; public SortedRunImpl(Run run) throws IOException { this.run = run; } @Override public int length() { return run.length; } @Override public Item get(int offset) { try { return ra.get(offset); } catch (IOException e) { throw new IllegalStateException(e); } } public void close() { if (ra != null) ra.close(); ra = null; } @Override public void open() throws IOException { this.ra = new RunInputRandomAccess(run); } } private Run mergeAll(List<Partition> partitions) throws IOException { // enqueue partition merge int id = 0; List<PartitionMergeTask> tasks = new ArrayList<PartitionMergeTask>(); for (Partition p : partitions) { List<Run> runParts = new LinkedList<Run>(); for (SortedRunRange range : p.getRunRanges()) { SortedRunImpl ri = (SortedRunImpl) range.getRun(); Run run = ri.run; int newId = runIndexer.incrementAndGet(); if (run.cached != null) { List<Item> sublist = run.cached.subList(range.getFrom(), range.getTo() + 1); Run r = new Run(newId, sublist); runParts.add(r); } else { Run r = new Run(newId, range.length(), run.indexFile.share(), run.dataFile.share(), range.getFrom()); runParts.add(r); } } if (runParts.size() > 0) { PartitionMergeTask task = new PartitionMergeTask(id++, runParts); tasks.add(task); } } mergeLatch = new CountDownLatch(tasks.size()); for (PartitionMergeTask task : tasks) { merges.add(task); executor.submit(new MergeWorker(task)); } // wait partition merge - try { - mergeLatch.await(); - } catch (InterruptedException e) { + while (mergeLatch.getCount() > 0) { + try { + mergeLatch.await(); + } catch (InterruptedException e) { + logger.debug("araqne logdb: merge latch interrupted at count [{}]", mergeLatch.getCount()); + } } // final merge ArrayList<PartitionMergeTask> l = new ArrayList<PartitionMergeTask>(); while (true) { PartitionMergeTask t = merges.poll(); if (t == null) break; l.add(t); } Collections.sort(l); ArrayList<Run> finalRuns = new ArrayList<Run>(); for (PartitionMergeTask t : l) { finalRuns.add(t.output); } return concat(finalRuns); } private class FlushWorker implements Runnable { private LinkedList<Item> buffered; public FlushWorker(LinkedList<Item> list) { buffered = list; } @Override public void run() { try { doFlush(); } catch (Throwable t) { logger.error("araqne logdb: failed to flush", t); } finally { synchronized (flushDoneSignal) { flushTaskCount--; flushDoneSignal.notifyAll(); } } } private void doFlush() throws IOException { Collections.sort(buffered, comparator); int id = runIndexer.incrementAndGet(); RunOutput out = new RunOutput(id, buffered.size(), cacheCount); try { for (Item o : buffered) out.write(o); } finally { Run run = out.finish(); runs.add(run); } } } private class MergeWorker implements Runnable { private PartitionMergeTask task; public MergeWorker(PartitionMergeTask task) { this.task = task; } @Override public void run() { try { Run merged = mergeRuns(task.runs); logger.debug("araqne logdb: merged run {}, input runs: {}", merged, task.runs); task.output = merged; } catch (Throwable t) { logger.error("araqne logdb: failed to merge " + task.runs, t); } finally { mergeLatch.countDown(); } } private Run mergeRuns(List<Run> runs) throws IOException { if (runs.size() == 1) return runs.get(0); List<Run> phase = new ArrayList<Run>(); for (int i = 0; i < 8; i++) { if (!runs.isEmpty()) phase.add(runs.remove(0)); } runs.add(merge(phase)); return mergeRuns(runs); } } private void writeRestObjects(RunInput in, RunOutput out) throws IOException { int count = 0; while (in.hasNext()) { out.write(in.next()); count++; } logger.debug("araqne logdb: final output writing from run #{}, count={}", in.getId(), count); } private Run concat(List<Run> finalRuns) throws IOException { logger.debug("araqne logdb: concat begins"); RunOutput out = null; List<RunInput> inputs = new LinkedList<RunInput>(); try { int total = 0; for (Run r : finalRuns) { total += r.length; inputs.add(new RunInput(r, cacheCount)); logger.debug("araqne logdb: concat run #{}", r.id); } int id = runIndexer.incrementAndGet(); out = new RunOutput(id, total, cacheCount, true); for (RunInput in : inputs) { writeRestObjects(in, out); if (out.dataBos != null) out.dataBos.flush(); } } catch (Exception e) { logger.error("araqne logdb: failed to concat " + finalRuns, e); } finally { for (RunInput input : inputs) { input.purge(); } if (out != null) return out.finish(); } return null; } private Run merge(List<Run> runs) throws IOException { if (runs.size() == 0) throw new IllegalArgumentException("runs should not be empty"); if (runs.size() == 1) { return runs.get(0); } logger.debug("araqne logdb: begin {}way merge, {}", runs.size(), runs); ArrayList<RunInput> inputs = new ArrayList<RunInput>(); PriorityQueue<RunItem> q = new PriorityQueue<RunItem>(runs.size(), new RunItemComparater()); RunOutput r3 = null; try { int total = 0; for (Run r : runs) { inputs.add(new RunInput(r, cacheCount)); total += r.length; } int id = runIndexer.incrementAndGet(); r3 = new RunOutput(id, total, cacheCount, true); while (true) { // load next inputs for (RunInput input : inputs) { if (input.loaded == null && input.hasNext()) { input.loaded = input.next(); q.add(new RunItem(input, input.loaded)); } } RunItem item = q.poll(); if (item == null) break; r3.write(item.item); item.runInput.loaded = null; } } finally { for (RunInput input : inputs) input.purge(); if (r3 != null) return r3.finish(); } logger.error("araqne logdb: merge cannot reach here, bug check!"); return null; } private class RunItemComparater implements Comparator<RunItem> { @Override public int compare(RunItem o1, RunItem o2) { return comparator.compare(o1.item, o2.item); } } private static class RunItem { private RunInput runInput; private Item item; public RunItem(RunInput runInput, Item item) { this.runInput = runInput; this.item = item; } } private class PartitionMergeTask implements Comparable<PartitionMergeTask> { private int id; private List<Run> runs; private Run output; public PartitionMergeTask(int id, List<Run> runs) { this.id = id; this.runs = runs; } @Override public int compareTo(PartitionMergeTask o) { return id - o.id; } } }
true
true
private Run mergeAll(List<Partition> partitions) throws IOException { // enqueue partition merge int id = 0; List<PartitionMergeTask> tasks = new ArrayList<PartitionMergeTask>(); for (Partition p : partitions) { List<Run> runParts = new LinkedList<Run>(); for (SortedRunRange range : p.getRunRanges()) { SortedRunImpl ri = (SortedRunImpl) range.getRun(); Run run = ri.run; int newId = runIndexer.incrementAndGet(); if (run.cached != null) { List<Item> sublist = run.cached.subList(range.getFrom(), range.getTo() + 1); Run r = new Run(newId, sublist); runParts.add(r); } else { Run r = new Run(newId, range.length(), run.indexFile.share(), run.dataFile.share(), range.getFrom()); runParts.add(r); } } if (runParts.size() > 0) { PartitionMergeTask task = new PartitionMergeTask(id++, runParts); tasks.add(task); } } mergeLatch = new CountDownLatch(tasks.size()); for (PartitionMergeTask task : tasks) { merges.add(task); executor.submit(new MergeWorker(task)); } // wait partition merge try { mergeLatch.await(); } catch (InterruptedException e) { } // final merge ArrayList<PartitionMergeTask> l = new ArrayList<PartitionMergeTask>(); while (true) { PartitionMergeTask t = merges.poll(); if (t == null) break; l.add(t); } Collections.sort(l); ArrayList<Run> finalRuns = new ArrayList<Run>(); for (PartitionMergeTask t : l) { finalRuns.add(t.output); } return concat(finalRuns); }
private Run mergeAll(List<Partition> partitions) throws IOException { // enqueue partition merge int id = 0; List<PartitionMergeTask> tasks = new ArrayList<PartitionMergeTask>(); for (Partition p : partitions) { List<Run> runParts = new LinkedList<Run>(); for (SortedRunRange range : p.getRunRanges()) { SortedRunImpl ri = (SortedRunImpl) range.getRun(); Run run = ri.run; int newId = runIndexer.incrementAndGet(); if (run.cached != null) { List<Item> sublist = run.cached.subList(range.getFrom(), range.getTo() + 1); Run r = new Run(newId, sublist); runParts.add(r); } else { Run r = new Run(newId, range.length(), run.indexFile.share(), run.dataFile.share(), range.getFrom()); runParts.add(r); } } if (runParts.size() > 0) { PartitionMergeTask task = new PartitionMergeTask(id++, runParts); tasks.add(task); } } mergeLatch = new CountDownLatch(tasks.size()); for (PartitionMergeTask task : tasks) { merges.add(task); executor.submit(new MergeWorker(task)); } // wait partition merge while (mergeLatch.getCount() > 0) { try { mergeLatch.await(); } catch (InterruptedException e) { logger.debug("araqne logdb: merge latch interrupted at count [{}]", mergeLatch.getCount()); } } // final merge ArrayList<PartitionMergeTask> l = new ArrayList<PartitionMergeTask>(); while (true) { PartitionMergeTask t = merges.poll(); if (t == null) break; l.add(t); } Collections.sort(l); ArrayList<Run> finalRuns = new ArrayList<Run>(); for (PartitionMergeTask t : l) { finalRuns.add(t.output); } return concat(finalRuns); }
diff --git a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/impl/mysql/MySQLDatabaseGeneratorImpl.java b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/impl/mysql/MySQLDatabaseGeneratorImpl.java index 0ccf01e..8f38552 100644 --- a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/impl/mysql/MySQLDatabaseGeneratorImpl.java +++ b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/impl/mysql/MySQLDatabaseGeneratorImpl.java @@ -1,375 +1,373 @@ package net.madz.db.core.impl.mysql; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.List; import net.madz.db.core.AbsDatabaseGenerator; import net.madz.db.core.meta.immutable.ForeignKeyMetaData; import net.madz.db.core.meta.immutable.IndexMetaData.Entry; import net.madz.db.core.meta.immutable.mysql.MySQLColumnMetaData; import net.madz.db.core.meta.immutable.mysql.MySQLForeignKeyMetaData; import net.madz.db.core.meta.immutable.mysql.MySQLIndexMetaData; import net.madz.db.core.meta.immutable.mysql.MySQLSchemaMetaData; import net.madz.db.core.meta.immutable.mysql.MySQLTableMetaData; import net.madz.db.core.meta.immutable.types.KeyTypeEnum; import net.madz.db.utils.MessageConsts; public class MySQLDatabaseGeneratorImpl extends AbsDatabaseGenerator<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> { public MySQLDatabaseGeneratorImpl() { } @Override public String generateDatabase(final MySQLSchemaMetaData metaData, final Connection conn, final String targetDatabaseName) throws SQLException { if ( null == targetDatabaseName || 0 >= targetDatabaseName.length() ) { throw new IllegalArgumentException("Target " + MessageConsts.DATABASE_NAME_SHOULD_NOT_BE_NULL); } GenerateDatabase(metaData, conn, targetDatabaseName); // Generate tables GenerateTables(metaData, conn, targetDatabaseName); // Generate foreign keys GenerateForeignKeys(metaData, conn, targetDatabaseName); return targetDatabaseName; } private void GenerateDatabase(final MySQLSchemaMetaData metaData, final Connection conn, final String targetDatabaseName) throws SQLException { final Statement stmt = conn.createStatement(); final StringBuilder result = new StringBuilder(); result.append("CREATE DATABASE IF NOT EXISTS "); result.append(targetDatabaseName); if ( null != metaData.getCharSet() && 0 < metaData.getCharSet().length() ) { result.append(" DEFAULT CHARACTER SET = '"); result.append(metaData.getCharSet()); result.append("'"); } if ( null != metaData.getCollation() && 0 < metaData.getCollation().length() ) { result.append(" DEFAULT COLLATE = '"); result.append(metaData.getCollation()); result.append("'"); } result.append(";"); stmt.execute(result.toString()); } /** * @param metaData * @param conn * @param targetDatabaseName * @throws SQLException */ private void GenerateTables(final MySQLSchemaMetaData metaData, final Connection conn, final String targetDatabaseName) throws SQLException { final Statement stmt = conn.createStatement(); conn.setAutoCommit(false); stmt.executeUpdate("USE `" + targetDatabaseName + "`"); for ( final MySQLTableMetaData table : metaData.getTables() ) { final StringBuilder result = new StringBuilder(); result.append("CREATE TABLE IF NOT EXISTS `"); result.append(table.getTableName()); result.append("` ("); if ( 0 >= table.getColumns().size() ) { throw new IllegalStateException("Table: " + table.getTableName() + " has no columns."); } for ( final MySQLColumnMetaData column : table.getColumns() ) { appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); appendSpace(result); if ( null != column.getColumnType() ) { result.append(column.getColumnType()); - appendCharSet(result, column); - appendCollation(result, column); } else { result.append(assembleColumnType(column)); } if ( column.isNullable() ) { result.append(" NULL "); } else { result.append(" NOT NULL "); } if ( column.hasDefaultValue() ) { result.append(" DEFAULT "); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } result.append(column.getDefaultValue()); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } } if ( column.isAutoIncremented() ) { result.append(" AUTO_INCREMENT "); } if ( null != column.getRemarks() && 0 < column.getRemarks().length() ) { result.append(" COMMENT '"); result.append(column.getRemarks()); result.append("'"); appendSpace(result); } result.append(","); } result.deleteCharAt(result.length() - 1); // Append primary keys final MySQLIndexMetaData pk = table.getPrimaryKey(); if ( null != pk ) { Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = pk .getEntrySet(); if ( entrySet.size() > 0 ) { result.append(", PRIMARY KEY("); for ( Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { final MySQLColumnMetaData column = entry.getColumn(); appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); } } final Collection<MySQLIndexMetaData> indexSet = table.getIndexSet(); for ( MySQLIndexMetaData index : indexSet ) { final KeyTypeEnum keyType = index.getKeyType(); final Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index .getEntrySet(); // Append Unique keys if ( keyType.equals(KeyTypeEnum.uniqueKey) ) { result.append(","); result.append("UNIQUE KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); } // Append Indexes if ( keyType.equals(KeyTypeEnum.index) ) { result.append(","); result.append("KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); if ( null != index.getIndexType() ) { result.append("USING {"); result.append(index.getIndexType()); result.append("}"); } } } result.append(") "); if ( null != table.getEngine() && 0 <= table.getEngine().name().length() ) { result.append("ENGINE "); result.append(table.getEngine()); appendSpace(result); } if ( null != table.getCharacterSet() ) { result.append("CHARACTER SET "); result.append(table.getCharacterSet()); appendSpace(result); } if ( null != table.getCollation() ) { result.append("COLLATE "); result.append(table.getCollation()); appendSpace(result); } if ( null != table.getRemarks() && 0 < table.getRemarks().length() ) { result.append("COMMENT '"); result.append(table.getRemarks()); result.append("'"); appendSpace(result); } result.append(";"); System.out.println(result.toString()); stmt.addBatch(result.toString()); } stmt.executeBatch(); conn.commit(); } private void appendCollation(final StringBuilder result, final MySQLColumnMetaData column) { if ( null != column.getCollationName() ) { result.append(" COLLATE "); result.append(column.getCollationName()); appendSpace(result); } } private void appendCharSet(final StringBuilder result, final MySQLColumnMetaData column) { if ( null != column.getCharacterSet() ) { result.append(" CHARACTER SET "); result.append(column.getCharacterSet()); appendSpace(result); } } private String assembleColumnType(final MySQLColumnMetaData column) { final StringBuilder result = new StringBuilder(); String sqlTypeName = column.getSqlTypeName(); if ( null == sqlTypeName ) { throw new IllegalArgumentException(MessageConsts.SQL_TYPE_NAME_IS_NULL); } if ( sqlTypeName.equalsIgnoreCase("BIT") || sqlTypeName.equalsIgnoreCase("BINARY") || sqlTypeName.equalsIgnoreCase("VARBINARY") ) { result.append(sqlTypeName); result.append("("); result.append(column.getNumericPrecision()); result.append(") "); } else if ( sqlTypeName.equalsIgnoreCase("TINYINT") || sqlTypeName.equalsIgnoreCase("SMALLINT") || sqlTypeName.equalsIgnoreCase("MEDIUMINT") || sqlTypeName.equalsIgnoreCase("INT") || sqlTypeName.equalsIgnoreCase("INTEGER") || sqlTypeName.equalsIgnoreCase("BIGINT") ) { result.append(sqlTypeName); result.append("("); result.append(column.getNumericPrecision()); result.append(")"); appendSpace(result); if ( column.isUnsigned() ) { result.append("UNSIGNED"); appendSpace(result); } if ( column.isZeroFill() ) { result.append("ZEROFILL"); appendSpace(result); } } else if ( sqlTypeName.equalsIgnoreCase("REAL") || sqlTypeName.equalsIgnoreCase("DOUBLE") || sqlTypeName.equalsIgnoreCase("FLOAT") || sqlTypeName.equalsIgnoreCase("DECIMAL") || sqlTypeName.equalsIgnoreCase("NUMERIC") ) { result.append(sqlTypeName); result.append("("); result.append(column.getNumericPrecision()); result.append(","); result.append(column.getNumericScale()); result.append(")"); if ( column.isUnsigned() ) { result.append("UNSIGNED"); appendSpace(result); } if ( column.isZeroFill() ) { result.append("ZEROFILL"); appendSpace(result); } } else if ( sqlTypeName.equalsIgnoreCase("CHAR") || sqlTypeName.equalsIgnoreCase("VARCHAR") ) { result.append(sqlTypeName); result.append("("); result.append(column.getCharacterMaximumLength()); result.append(")"); appendSpace(result); appendCharSet(result, column); if ( column.isCollationWithBin() ) { result.append(" BINARY "); } appendCollation(result, column); } else if ( sqlTypeName.equalsIgnoreCase("TINYTEXT") || sqlTypeName.equalsIgnoreCase("TEXT") || sqlTypeName.equalsIgnoreCase("MEDIUMTEXT") || sqlTypeName.equalsIgnoreCase("LONGTEXT") ) { result.append(sqlTypeName); if ( column.isCollationWithBin() ) { appendSpace(result); result.append("BINARY"); appendSpace(result); } appendCharSet(result, column); appendCollation(result, column); } else if ( sqlTypeName.toUpperCase().contains("ENUM") || sqlTypeName.toUpperCase().contains("SET") ) { result.append(sqlTypeName); result.append("("); for ( String value : column.getTypeValues() ) { result.append(value); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); appendSpace(result); appendCharSet(result, column); appendCollation(result, column); } else { result.append(sqlTypeName); } return result.toString(); } private void GenerateForeignKeys(MySQLSchemaMetaData metaData, Connection conn, String targetDatabaseName) throws SQLException { final Statement stmt = conn.createStatement(); stmt.execute("USE " + targetDatabaseName + ";"); final Collection<MySQLTableMetaData> tables = metaData.getTables(); for ( MySQLTableMetaData table : tables ) { final Collection<MySQLForeignKeyMetaData> foreignKeySet = table.getForeignKeySet(); if ( null != foreignKeySet && 0 < foreignKeySet.size() ) { for ( MySQLForeignKeyMetaData fk : foreignKeySet ) { final StringBuilder result = new StringBuilder(); result.append("ALTER TABLE "); appendBackQuotation(result); result.append(table.getTableName()); appendBackQuotation(result); appendSpace(result); result.append("ADD "); if ( null != fk.getForeignKeyName() && 0 < fk.getForeignKeyName().length() ) { result.append("CONSTRAINT "); appendBackQuotation(result); result.append(fk.getForeignKeyName()); appendBackQuotation(result); } result.append("FOREIGN KEY "); if ( null != fk.getForeignKeyIndex() && 0 < fk.getForeignKeyIndex().getIndexName().length() ) { result.append(fk.getForeignKeyIndex().getIndexName()); } result.append("("); final List<ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = fk .getEntrySet(); for ( ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { appendBackQuotation(result); result.append(entry.getForeignKeyColumn().getColumnName()); appendBackQuotation(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); appendSpace(result); result.append("REFERENCES "); appendBackQuotation(result); result.append(fk.getPrimaryKeyTable().getTableName()); appendBackQuotation(result); result.append("("); for ( ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { appendBackQuotation(result); result.append(entry.getPrimaryKeyColumn().getColumnName()); appendBackQuotation(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(");"); System.out.println(result.toString()); stmt.addBatch(result.toString()); } } } stmt.executeBatch(); conn.commit(); } private void appendIndexEntries(final StringBuilder result, final Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet) { for ( Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { appendBackQuotation(result); result.append(entry.getColumn().getColumnName()); appendBackQuotation(result); appendSpace(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); } private void appendIndexName(final StringBuilder result, MySQLIndexMetaData index) { if ( null != index.getIndexName() && index.getIndexName().length() > 0 ) { appendSpace(result); appendBackQuotation(result); result.append(index.getIndexName()); appendBackQuotation(result); } } private void appendSpace(final StringBuilder result) { result.append(" "); } private void appendBackQuotation(final StringBuilder result) { result.append("`"); } }
true
true
private void GenerateTables(final MySQLSchemaMetaData metaData, final Connection conn, final String targetDatabaseName) throws SQLException { final Statement stmt = conn.createStatement(); conn.setAutoCommit(false); stmt.executeUpdate("USE `" + targetDatabaseName + "`"); for ( final MySQLTableMetaData table : metaData.getTables() ) { final StringBuilder result = new StringBuilder(); result.append("CREATE TABLE IF NOT EXISTS `"); result.append(table.getTableName()); result.append("` ("); if ( 0 >= table.getColumns().size() ) { throw new IllegalStateException("Table: " + table.getTableName() + " has no columns."); } for ( final MySQLColumnMetaData column : table.getColumns() ) { appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); appendSpace(result); if ( null != column.getColumnType() ) { result.append(column.getColumnType()); appendCharSet(result, column); appendCollation(result, column); } else { result.append(assembleColumnType(column)); } if ( column.isNullable() ) { result.append(" NULL "); } else { result.append(" NOT NULL "); } if ( column.hasDefaultValue() ) { result.append(" DEFAULT "); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } result.append(column.getDefaultValue()); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } } if ( column.isAutoIncremented() ) { result.append(" AUTO_INCREMENT "); } if ( null != column.getRemarks() && 0 < column.getRemarks().length() ) { result.append(" COMMENT '"); result.append(column.getRemarks()); result.append("'"); appendSpace(result); } result.append(","); } result.deleteCharAt(result.length() - 1); // Append primary keys final MySQLIndexMetaData pk = table.getPrimaryKey(); if ( null != pk ) { Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = pk .getEntrySet(); if ( entrySet.size() > 0 ) { result.append(", PRIMARY KEY("); for ( Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { final MySQLColumnMetaData column = entry.getColumn(); appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); } } final Collection<MySQLIndexMetaData> indexSet = table.getIndexSet(); for ( MySQLIndexMetaData index : indexSet ) { final KeyTypeEnum keyType = index.getKeyType(); final Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index .getEntrySet(); // Append Unique keys if ( keyType.equals(KeyTypeEnum.uniqueKey) ) { result.append(","); result.append("UNIQUE KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); } // Append Indexes if ( keyType.equals(KeyTypeEnum.index) ) { result.append(","); result.append("KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); if ( null != index.getIndexType() ) { result.append("USING {"); result.append(index.getIndexType()); result.append("}"); } } } result.append(") "); if ( null != table.getEngine() && 0 <= table.getEngine().name().length() ) { result.append("ENGINE "); result.append(table.getEngine()); appendSpace(result); } if ( null != table.getCharacterSet() ) { result.append("CHARACTER SET "); result.append(table.getCharacterSet()); appendSpace(result); } if ( null != table.getCollation() ) { result.append("COLLATE "); result.append(table.getCollation()); appendSpace(result); } if ( null != table.getRemarks() && 0 < table.getRemarks().length() ) { result.append("COMMENT '"); result.append(table.getRemarks()); result.append("'"); appendSpace(result); } result.append(";"); System.out.println(result.toString()); stmt.addBatch(result.toString()); } stmt.executeBatch(); conn.commit(); }
private void GenerateTables(final MySQLSchemaMetaData metaData, final Connection conn, final String targetDatabaseName) throws SQLException { final Statement stmt = conn.createStatement(); conn.setAutoCommit(false); stmt.executeUpdate("USE `" + targetDatabaseName + "`"); for ( final MySQLTableMetaData table : metaData.getTables() ) { final StringBuilder result = new StringBuilder(); result.append("CREATE TABLE IF NOT EXISTS `"); result.append(table.getTableName()); result.append("` ("); if ( 0 >= table.getColumns().size() ) { throw new IllegalStateException("Table: " + table.getTableName() + " has no columns."); } for ( final MySQLColumnMetaData column : table.getColumns() ) { appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); appendSpace(result); if ( null != column.getColumnType() ) { result.append(column.getColumnType()); } else { result.append(assembleColumnType(column)); } if ( column.isNullable() ) { result.append(" NULL "); } else { result.append(" NOT NULL "); } if ( column.hasDefaultValue() ) { result.append(" DEFAULT "); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } result.append(column.getDefaultValue()); if ( !column.getSqlTypeName().equalsIgnoreCase("BIT") ) { result.append("'"); } } if ( column.isAutoIncremented() ) { result.append(" AUTO_INCREMENT "); } if ( null != column.getRemarks() && 0 < column.getRemarks().length() ) { result.append(" COMMENT '"); result.append(column.getRemarks()); result.append("'"); appendSpace(result); } result.append(","); } result.deleteCharAt(result.length() - 1); // Append primary keys final MySQLIndexMetaData pk = table.getPrimaryKey(); if ( null != pk ) { Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = pk .getEntrySet(); if ( entrySet.size() > 0 ) { result.append(", PRIMARY KEY("); for ( Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) { final MySQLColumnMetaData column = entry.getColumn(); appendBackQuotation(result); result.append(column.getColumnName()); appendBackQuotation(result); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); } } final Collection<MySQLIndexMetaData> indexSet = table.getIndexSet(); for ( MySQLIndexMetaData index : indexSet ) { final KeyTypeEnum keyType = index.getKeyType(); final Collection<Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index .getEntrySet(); // Append Unique keys if ( keyType.equals(KeyTypeEnum.uniqueKey) ) { result.append(","); result.append("UNIQUE KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); } // Append Indexes if ( keyType.equals(KeyTypeEnum.index) ) { result.append(","); result.append("KEY"); appendIndexName(result, index); result.append("("); appendIndexEntries(result, entrySet); if ( null != index.getIndexType() ) { result.append("USING {"); result.append(index.getIndexType()); result.append("}"); } } } result.append(") "); if ( null != table.getEngine() && 0 <= table.getEngine().name().length() ) { result.append("ENGINE "); result.append(table.getEngine()); appendSpace(result); } if ( null != table.getCharacterSet() ) { result.append("CHARACTER SET "); result.append(table.getCharacterSet()); appendSpace(result); } if ( null != table.getCollation() ) { result.append("COLLATE "); result.append(table.getCollation()); appendSpace(result); } if ( null != table.getRemarks() && 0 < table.getRemarks().length() ) { result.append("COMMENT '"); result.append(table.getRemarks()); result.append("'"); appendSpace(result); } result.append(";"); System.out.println(result.toString()); stmt.addBatch(result.toString()); } stmt.executeBatch(); conn.commit(); }
diff --git a/src/main/java/org/mobiloc/lobgasp/App.java b/src/main/java/org/mobiloc/lobgasp/App.java index 2a84b49..883b4b9 100644 --- a/src/main/java/org/mobiloc/lobgasp/App.java +++ b/src/main/java/org/mobiloc/lobgasp/App.java @@ -1,44 +1,43 @@ package org.mobiloc.lobgasp; import java.util.logging.Level; import java.util.logging.Logger; import org.hibernate.Session; import org.mobiloc.lobgasp.util.HibernateUtil; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Geometry; import java.util.Iterator; import org.mobiloc.lobgasp.osm.parser.OSMParser; import org.mobiloc.lobgasp.osm.parser.model.OSM; /** * Hello world! * */ public class App { public static void main(String[] args) { System.out.println("Hello World!"); Session s = HibernateUtil.getSessionFactory().getCurrentSession(); s.beginTransaction(); Iterator l = s.createSQLQuery("SELECT ST_AsText(ST_Transform(way,94326)), name FROM planet_osm_point" + " WHERE amenity like 'pub' OR amenity like 'bar'" + " ORDER BY osm_id").list().iterator(); while (l.hasNext()) { Object[] row = (Object[]) l.next(); String loc = (String) row[0]; String name = (String) row[1]; System.out.println(name + ": " + loc); } try { - OSM osm = OSMParser.parse("map.osm.osm"); + OSM osm = OSMParser.parse("src/test/map.osm"); System.out.println(osm.getNodes().iterator().next().tags); - System.out.println("here"); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } }
false
true
public static void main(String[] args) { System.out.println("Hello World!"); Session s = HibernateUtil.getSessionFactory().getCurrentSession(); s.beginTransaction(); Iterator l = s.createSQLQuery("SELECT ST_AsText(ST_Transform(way,94326)), name FROM planet_osm_point" + " WHERE amenity like 'pub' OR amenity like 'bar'" + " ORDER BY osm_id").list().iterator(); while (l.hasNext()) { Object[] row = (Object[]) l.next(); String loc = (String) row[0]; String name = (String) row[1]; System.out.println(name + ": " + loc); } try { OSM osm = OSMParser.parse("map.osm.osm"); System.out.println(osm.getNodes().iterator().next().tags); System.out.println("here"); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }
public static void main(String[] args) { System.out.println("Hello World!"); Session s = HibernateUtil.getSessionFactory().getCurrentSession(); s.beginTransaction(); Iterator l = s.createSQLQuery("SELECT ST_AsText(ST_Transform(way,94326)), name FROM planet_osm_point" + " WHERE amenity like 'pub' OR amenity like 'bar'" + " ORDER BY osm_id").list().iterator(); while (l.hasNext()) { Object[] row = (Object[]) l.next(); String loc = (String) row[0]; String name = (String) row[1]; System.out.println(name + ": " + loc); } try { OSM osm = OSMParser.parse("src/test/map.osm"); System.out.println(osm.getNodes().iterator().next().tags); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }
diff --git a/transcript-jersey/src/main/java/uk/org/sappho/applications/restful/transcript/jersey/RestSession.java b/transcript-jersey/src/main/java/uk/org/sappho/applications/restful/transcript/jersey/RestSession.java index fb577e6..1b526e2 100644 --- a/transcript-jersey/src/main/java/uk/org/sappho/applications/restful/transcript/jersey/RestSession.java +++ b/transcript-jersey/src/main/java/uk/org/sappho/applications/restful/transcript/jersey/RestSession.java @@ -1,24 +1,24 @@ /** *** This software is licensed under the GNU General Public License, version 3. *** See http://www.gnu.org/licenses/gpl.html for full details of the license terms. *** Copyright 2012 Andrew Heald. */ package uk.org.sappho.applications.restful.transcript.jersey; import uk.org.sappho.applications.services.transcript.registry.ConfigurationException; public class RestSession { public interface Action<T> { void execute() throws ConfigurationException; T getResponse(); } - synchronized public void execute(Action session) throws ConfigurationException { + synchronized public void execute(Action action) throws ConfigurationException { - session.execute(); + action.execute(); } }
false
true
synchronized public void execute(Action session) throws ConfigurationException { session.execute(); }
synchronized public void execute(Action action) throws ConfigurationException { action.execute(); }
diff --git a/src/main/java/water/exec/ASTFunc.java b/src/main/java/water/exec/ASTFunc.java index 6b4364fbb..307e841b2 100644 --- a/src/main/java/water/exec/ASTFunc.java +++ b/src/main/java/water/exec/ASTFunc.java @@ -1,119 +1,118 @@ package water.exec; import java.util.ArrayList; import water.H2O; import water.Key; import water.fvec.AppendableVec; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; /** Parse a generic R string and build an AST, in the context of an H2O Cloud * @author [email protected] */ // -------------------------------------------------------------------------- public class ASTFunc extends ASTOp { final AST _body; final int _tmps; Env _env; // Captured environment at each apply point ASTFunc( String vars[], Type vtypes[], AST body, int tmps ) { super(vars,vtypes,OPF_PREFIX,OPP_PREFIX,OPA_RIGHT); _body = body; _tmps=tmps; } ASTFunc( String vars[], Type t, AST body, int tmps ){ super(vars,t,OPF_PREFIX,OPP_PREFIX,OPA_RIGHT); _body = body; _tmps=tmps; } @Override String opStr() { return "fun"; } //@Override ASTOp make() { throw H2O.fail();} @Override ASTOp make() { return new ASTFunc(_vars, _t.copy(), _body, _tmps); } static ASTOp parseFcn(Exec2 E ) { int x = E._x; String var = E.isID(); if( var == null ) return null; if( !"function".equals(var) ) { E._x = x; return null; } E.xpeek('(',E._x,null); ArrayList<ASTId> vars = new ArrayList<ASTId>(); if( !E.peek(')') ) { while( true ) { x = E._x; var = E.isID(); if( var == null ) E.throwErr("Invalid var",x); for( ASTId id : vars ) if( var.equals(id._id) ) E.throwErr("Repeated argument",x); // Add unknown-type variable to new vars list vars.add(new ASTId(Type.unbound(),var,0,vars.size())); if( E.peek(')') ) break; E.xpeek(',',E._x,null); } } int argcnt = vars.size(); // Record current size, as body may extend // Parse the body - E.xpeek('{',(x=E._x),null); E._env.push(vars); - AST body = E.xpeek('}',E._x,ASTStatement.parse(E)); + AST body = E.peek('{') ? E.xpeek('}',E._x,ASTStatement.parse(E)) : parseCXExpr(E); if( body == null ) E.throwErr("Missing function body",x); E._env.pop(); // The body should force the types. Build a type signature. String xvars[] = new String[argcnt+1]; Type types[] = new Type [argcnt+1]; xvars[0] = "fun"; types[0] = body._t; // Return type of body for( int i=0; i<argcnt; i++ ) { ASTId id = vars.get(i); xvars[i+1] = id._id; types[i+1] = id._t; } return new ASTFunc(xvars,types,body,vars.size()-argcnt); } @Override void exec(Env env) { // We need to push a Closure: the ASTFunc plus captured environment. // Make a shallow copy (the body remains shared across all ASTFuncs). // Then fill in the current environment. ASTFunc fun = (ASTFunc)clone(); fun._env = env.capture(); env.push(fun); } @Override void apply(Env env, int argcnt) { int res_idx = env.pushScope(argcnt-1); env.push(_tmps); _body.exec(env); env.tos_into_slot(res_idx-1,null); env.popScope(); } @Override double[] map(Env env, double[] in, double[] out) { final int sp = env._sp; Key key = Vec.VectorGroup.VG_LEN1.addVecs(1)[0]; AppendableVec av = new AppendableVec(key); NewChunk nc = new NewChunk(av,0); for (double v : in) nc.addNum(v); nc.close(0,null); Frame fr = new Frame(av.close(null)); env.push(this); env.push(fr); this.apply(env,2); if (env.isDbl()) { if (out==null || out.length<1) out= new double[1]; out[0] = env.popDbl(); } else if (env.isAry()) { fr = env.peekAry(); if (fr.vecs().length > 1) H2O.unimpl(); Vec vec = fr.anyVec(); if (vec.length() > 1<<8) H2O.unimpl(); if (out==null || out.length<vec.length()) out= new double[(int)vec.length()]; for (long i = 0; i < vec.length(); i++) out[(int)i] = vec.at(i); env.pop(); } else { H2O.unimpl(); } assert sp == env._sp; return out; } @Override public StringBuilder toString( StringBuilder sb, int d ) { indent(sb,d).append(this).append(") {\n"); _body.toString(sb,d+1).append("\n"); return indent(sb,d).append("}"); } }
false
true
static ASTOp parseFcn(Exec2 E ) { int x = E._x; String var = E.isID(); if( var == null ) return null; if( !"function".equals(var) ) { E._x = x; return null; } E.xpeek('(',E._x,null); ArrayList<ASTId> vars = new ArrayList<ASTId>(); if( !E.peek(')') ) { while( true ) { x = E._x; var = E.isID(); if( var == null ) E.throwErr("Invalid var",x); for( ASTId id : vars ) if( var.equals(id._id) ) E.throwErr("Repeated argument",x); // Add unknown-type variable to new vars list vars.add(new ASTId(Type.unbound(),var,0,vars.size())); if( E.peek(')') ) break; E.xpeek(',',E._x,null); } } int argcnt = vars.size(); // Record current size, as body may extend // Parse the body E.xpeek('{',(x=E._x),null); E._env.push(vars); AST body = E.xpeek('}',E._x,ASTStatement.parse(E)); if( body == null ) E.throwErr("Missing function body",x); E._env.pop(); // The body should force the types. Build a type signature. String xvars[] = new String[argcnt+1]; Type types[] = new Type [argcnt+1]; xvars[0] = "fun"; types[0] = body._t; // Return type of body for( int i=0; i<argcnt; i++ ) { ASTId id = vars.get(i); xvars[i+1] = id._id; types[i+1] = id._t; } return new ASTFunc(xvars,types,body,vars.size()-argcnt); }
static ASTOp parseFcn(Exec2 E ) { int x = E._x; String var = E.isID(); if( var == null ) return null; if( !"function".equals(var) ) { E._x = x; return null; } E.xpeek('(',E._x,null); ArrayList<ASTId> vars = new ArrayList<ASTId>(); if( !E.peek(')') ) { while( true ) { x = E._x; var = E.isID(); if( var == null ) E.throwErr("Invalid var",x); for( ASTId id : vars ) if( var.equals(id._id) ) E.throwErr("Repeated argument",x); // Add unknown-type variable to new vars list vars.add(new ASTId(Type.unbound(),var,0,vars.size())); if( E.peek(')') ) break; E.xpeek(',',E._x,null); } } int argcnt = vars.size(); // Record current size, as body may extend // Parse the body E._env.push(vars); AST body = E.peek('{') ? E.xpeek('}',E._x,ASTStatement.parse(E)) : parseCXExpr(E); if( body == null ) E.throwErr("Missing function body",x); E._env.pop(); // The body should force the types. Build a type signature. String xvars[] = new String[argcnt+1]; Type types[] = new Type [argcnt+1]; xvars[0] = "fun"; types[0] = body._t; // Return type of body for( int i=0; i<argcnt; i++ ) { ASTId id = vars.get(i); xvars[i+1] = id._id; types[i+1] = id._t; } return new ASTFunc(xvars,types,body,vars.size()-argcnt); }
diff --git a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/compiler/CompcMojo.java b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/compiler/CompcMojo.java index b21a89881..e9b6b38fb 100644 --- a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/compiler/CompcMojo.java +++ b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/compiler/CompcMojo.java @@ -1,437 +1,439 @@ /** * Flexmojos is a set of maven goals to allow maven users to compile, optimize and test Flex SWF, Flex SWC, Air SWF and Air SWC. * Copyright (C) 2008-2012 Marvin Froeder <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sonatype.flexmojos.plugin.compiler; import static org.sonatype.flexmojos.plugin.common.FlexExtension.RB_SWC; import static org.sonatype.flexmojos.plugin.common.FlexExtension.SWC; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.maven.model.FileSet; import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.DirectoryScanner; import org.sonatype.flexmojos.compiler.ICompcConfiguration; import org.sonatype.flexmojos.compiler.IIncludeFile; import org.sonatype.flexmojos.compiler.IIncludeStylesheet; import org.sonatype.flexmojos.compiler.command.Result; import org.sonatype.flexmojos.plugin.compiler.attributes.MavenIncludeStylesheet; import org.sonatype.flexmojos.plugin.compiler.attributes.converter.SimplifiablePattern; import org.sonatype.flexmojos.util.PathUtil; /** * <p> * Goal which compiles the Flex sources into a library for either Flex or AIR depending. * </p> * <p> * The Flex Compiler plugin compiles all ActionScript sources. It can compile the source into 'swc' files. The plugin * supports the 'swc' packaging. * </p> * * @author Marvin Herman Froeder ([email protected]) * @since 1.0 * @goal compile-swc * @requiresDependencyResolution compile * @phase compile * @configurator flexmojos * @threadSafe */ public class CompcMojo extends AbstractFlexCompilerMojo<ICompcConfiguration, CompcMojo> implements ICompcConfiguration, Mojo { /** * Writes a digest to the catalog.xml of a library. This is required when the library will be used as runtime shared * libraries * <p> * Equivalent to -compute-digest * </p> * * @parameter expression="${flex.computeDigest}" */ protected Boolean computeDigest; /** * Output the library as an open directory instead of a SWC file * <p> * Equivalent to -directory * </p> * * @parameter expression="${flex.directory}" */ private Boolean directory; /** * Automatically include all declared namespaces * * @parameter default-value="false" expression="${flex.includeAllNamespaces}" */ private boolean includeAllNamespaces; /** * Inclusion/exclusion patterns used to filter classes to include in the output SWC * <p> * Equivalent to -include-classes * </p> * Usage: * * <pre> * &lt;includeClasses&gt; * &lt;include&gt;org.sonatype.flexmojos.MyClass&lt;/include&gt; * &lt;include&gt;org.sonatype.flexmojos.YourClass&lt;/include&gt; * &lt;scan&gt; * &lt;includes&gt; * &lt;include&gt;com.mycompany.*&lt;/include&gt; * &lt;/includes&gt; * &lt;excludes&gt; * &lt;exclude&gt;com.mycompany.ui.*&lt;/exclude&gt; * &lt;/excludes&gt; * &lt;/scan&gt; * &lt;scan&gt; * &lt;includes&gt; * &lt;include&gt;org.mycompany.*&lt;/include&gt; * &lt;/includes&gt; * &lt;excludes&gt; * &lt;exclude&gt;org.mycompany.ui.*&lt;/exclude&gt; * &lt;/excludes&gt; * &lt;/scan&gt; * &lt;/includeClasses&gt; * </pre> * * @parameter */ private SimplifiablePattern includeClasses; /** * Inclusion/exclusion patterns used to filter resources to be include in the output SWC * <p> * Equivalent to -include-file * </p> * Usage: * * <pre> * &lt;includeFiles&gt; * &lt;include&gt;afile.xml&lt;/include&gt; * &lt;include&gt;b.txt&lt;/include&gt; * &lt;scan&gt; * &lt;includes&gt; * &lt;include&gt;**\/*.rxml&lt;/include&gt; * &lt;/includes&gt; * &lt;excludes&gt; * &lt;exclude&gt;private/*&lt;/exclude&gt; * &lt;/excludes&gt; * &lt;/scan&gt; * &lt;/includeFiles&gt; * </pre> * * @parameter */ protected SimplifiablePattern includeFiles; /** * If true, manifest entries with lookupOnly=true are included in SWC catalog * <p> * Equivalent to -include-lookup-only * </p> * * @parameter expression="${flex.includeLookupOnly}" */ private Boolean includeLookupOnly; /** * All classes in the listed namespaces are included in the output SWC * <p> * Equivalent to -include-namespaces * </p> * Usage: * * <pre> * &lt;includeNamespaces&gt; * &lt;namespace&gt;http://mynamespace.com&lt;/namespace&gt; * &lt;/includeNamespaces&gt; * </pre> * * @parameter */ private List<String> includeNamespaces; /** * A list of directories and source files to include in the output SWC * <p> * Equivalent to -include-sources * </p> * Usage: * * <pre> * &lt;includeSources&gt; * &lt;includeSource&gt;${project.build.sourceDirectory}&lt;/includeSource&gt; * &lt;/includeSources&gt; * </pre> * * @parameter */ private File[] includeSources; /** * A list of named stylesheet resources to include in the output SWC * <p> * Equivalent to -include-stylesheet * </p> * Usage: * * <pre> * &lt;includeStylesheets&gt; * &lt;stylesheet&gt; * &lt;name&gt;mystyle.css&lt;/name&gt; * &lt;path&gt;${basedir}/mystyle.css&lt;/path&gt; * &lt;/stylesheet&gt; * &lt;/includeStylesheets&gt; * </pre> * * @parameter */ private MavenIncludeStylesheet[] includeStylesheets; /** * DOCME Guess what, undocumented by adobe. Looks like it was overwritten by source paths * <p> * Equivalent to -root * </p> * * @parameter expression="${flex.root}" * @deprecated */ private String root; @Override public Result doCompile( ICompcConfiguration cfg, boolean synchronize ) throws Exception { return compiler.compileSwc( cfg, synchronize ); } public void execute() throws MojoExecutionException, MojoFailureException { if ( !( PathUtil.existAny( getSourcePath() ) || getIncludeFile() != null ) ) { getLog().warn( "Skipping compiler, nothing available to be included on swc." ); return; } executeCompiler( this, true ); if ( getLocalesRuntime() != null ) { List<Result> results = new ArrayList<Result>(); for ( String locale : getLocalesRuntime() ) { CompcMojo cfg = this.clone(); configureResourceBundle( locale, cfg ); cfg.getCache().put( "getProjectType", RB_SWC ); results.add( executeCompiler( cfg, fullSynchronization ) ); } wait( results ); } } public Boolean getComputeDigest() { return computeDigest; } public Boolean getDirectory() { return directory; } public List<String> getIncludeClasses() { if ( includeClasses == null ) { return null; } List<String> classes = new ArrayList<String>(); classes.addAll( includeClasses.getIncludes() ); classes.addAll( filterClasses( includeClasses.getPatterns(), getSourcePath() ) ); return classes; } public IIncludeFile[] getIncludeFile() { List<IIncludeFile> files = new ArrayList<IIncludeFile>(); List<FileSet> patterns = new ArrayList<FileSet>(); if ( includeFiles == null && includeNamespaces == null && includeSources == null && includeClasses == null ) { patterns.addAll( resources ); } else if ( includeFiles == null ) { return null; } else { + // process patterns patterns.addAll( includeFiles.getPatterns() ); + // process files for ( final String path : includeFiles.getIncludes() ) { final File file = PathUtil.file( path, getResourcesTargetDirectories() ); files.add( new IIncludeFile() { public String name() { return path.replace( '\\', '/' ); } public String path() { return file.getAbsolutePath(); } } ); } } for ( FileSet pattern : patterns ) { final DirectoryScanner scan = scan( pattern ); if ( scan == null ) { continue; } for ( final String file : scan.getIncludedFiles() ) { files.add( new IIncludeFile() { public String name() { - return file; + return file.replace( '\\', '/' ); } public String path() { return PathUtil.file( file, scan.getBasedir() ).getAbsolutePath(); } } ); } } return files.toArray( new IIncludeFile[0] ); } public Boolean getIncludeLookupOnly() { return includeLookupOnly; } public List<String> getIncludeNamespaces() { if ( includeNamespaces != null ) { return includeNamespaces; } if ( includeAllNamespaces ) { return getNamespacesUri(); } return null; } public List<String> getIncludeResourceBundles() { return includeResourceBundles; } public File[] getIncludeSources() { if ( includeFiles == null && getIncludeNamespaces() == null && includeSources == null && includeClasses == null ) { return getSourcePath(); } return includeSources; } public IIncludeStylesheet[] getIncludeStylesheet() { if ( includeStylesheets == null ) { return null; } IIncludeStylesheet[] is = new IIncludeStylesheet[includeStylesheets.length]; for ( int i = 0; i < includeStylesheets.length; i++ ) { final MavenIncludeStylesheet ss = includeStylesheets[i]; is[i] = new IIncludeStylesheet() { public String name() { if ( ss.getName() != null ) { return ss.getName(); } return PathUtil.file( ss.getPath(), getResourcesTargetDirectories() ).getName(); } public String path() { return PathUtil.file( ss.getPath(), getResourcesTargetDirectories() ).getAbsolutePath(); } }; } return is; } @Override public String[] getLocale() { String[] locale = super.getLocale(); if ( locale != null ) { return locale; } return new String[] {}; } @Override public String getProjectType() { return SWC; } public String getRoot() { return root; } }
false
true
public IIncludeFile[] getIncludeFile() { List<IIncludeFile> files = new ArrayList<IIncludeFile>(); List<FileSet> patterns = new ArrayList<FileSet>(); if ( includeFiles == null && includeNamespaces == null && includeSources == null && includeClasses == null ) { patterns.addAll( resources ); } else if ( includeFiles == null ) { return null; } else { patterns.addAll( includeFiles.getPatterns() ); for ( final String path : includeFiles.getIncludes() ) { final File file = PathUtil.file( path, getResourcesTargetDirectories() ); files.add( new IIncludeFile() { public String name() { return path.replace( '\\', '/' ); } public String path() { return file.getAbsolutePath(); } } ); } } for ( FileSet pattern : patterns ) { final DirectoryScanner scan = scan( pattern ); if ( scan == null ) { continue; } for ( final String file : scan.getIncludedFiles() ) { files.add( new IIncludeFile() { public String name() { return file; } public String path() { return PathUtil.file( file, scan.getBasedir() ).getAbsolutePath(); } } ); } } return files.toArray( new IIncludeFile[0] ); }
public IIncludeFile[] getIncludeFile() { List<IIncludeFile> files = new ArrayList<IIncludeFile>(); List<FileSet> patterns = new ArrayList<FileSet>(); if ( includeFiles == null && includeNamespaces == null && includeSources == null && includeClasses == null ) { patterns.addAll( resources ); } else if ( includeFiles == null ) { return null; } else { // process patterns patterns.addAll( includeFiles.getPatterns() ); // process files for ( final String path : includeFiles.getIncludes() ) { final File file = PathUtil.file( path, getResourcesTargetDirectories() ); files.add( new IIncludeFile() { public String name() { return path.replace( '\\', '/' ); } public String path() { return file.getAbsolutePath(); } } ); } } for ( FileSet pattern : patterns ) { final DirectoryScanner scan = scan( pattern ); if ( scan == null ) { continue; } for ( final String file : scan.getIncludedFiles() ) { files.add( new IIncludeFile() { public String name() { return file.replace( '\\', '/' ); } public String path() { return PathUtil.file( file, scan.getBasedir() ).getAbsolutePath(); } } ); } } return files.toArray( new IIncludeFile[0] ); }
diff --git a/annotation-detector/src/main/java/eu/infomas/annotation/ClassFileBuffer.java b/annotation-detector/src/main/java/eu/infomas/annotation/ClassFileBuffer.java index 924a7ad..f6020a8 100644 --- a/annotation-detector/src/main/java/eu/infomas/annotation/ClassFileBuffer.java +++ b/annotation-detector/src/main/java/eu/infomas/annotation/ClassFileBuffer.java @@ -1,240 +1,240 @@ /* ClassFileBuffer.java * * Created: 2011-10-10 (Year-Month-Day) * Character encoding: UTF-8 * ****************************************** LICENSE ******************************************* * * Copyright (c) 2011 - 2013 XIAM Solutions B.V. (http://www.xiam.nl) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.infomas.annotation; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * {@code ClassFileBuffer} is used by {@link AnnotationDetector} to efficiently read Java * ClassFile files from an {@link InputStream} and parse the content via the {@link DataInput} * interface. * <p> * Note that Java ClassFile files can grow really big, * {@code com.sun.corba.se.impl.logging.ORBUtilSystemException} is 128.2 kb! * * @author <a href="mailto:[email protected]">Ronald K. Muller</a> * @since annotation-detector 3.0.0 */ final class ClassFileBuffer implements DataInput { private byte[] buffer; private int size; // the number of significant bytes read private int pointer; // the "read pointer" /** * Create a new, empty {@code ClassFileBuffer} with the default initial capacity (8 kb). */ ClassFileBuffer() { this(8 * 1024); } /** * Create a new, empty {@code ClassFileBuffer} with the specified initial capacity. * The initial capacity must be greater than zero. The internal buffer will grow * automatically when a higher capacity is required. However, buffer resizing occurs * extra overhead. So in good initial capacity is important in performance critical * situations. */ ClassFileBuffer(final int initialCapacity) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity < 1: " + initialCapacity); } this.buffer = new byte[initialCapacity]; } /** * Clear and fill the buffer of this {@code ClassFileBuffer} with the * supplied byte stream. * The read pointer is reset to the start of the byte array. */ public void readFrom(final InputStream in) throws IOException { pointer = 0; size = 0; int n; do { n = in.read(buffer, size, buffer.length - size); if (n > 0) { size += n; } resizeIfNeeded(); } while (n >= 0); } /** * Sets the file-pointer offset, measured from the beginning of this file, * at which the next read or write occurs. */ public void seek(final int position) throws IOException { if (position < 0) { throw new IllegalArgumentException("position < 0: " + position); } if (position > size) { throw new EOFException(); } this.pointer = position; } /** * Return the size (in bytes) of this Java ClassFile file. */ public int size() { return size; } // DataInput @Override public void readFully(final byte[] bytes) throws IOException { readFully(bytes, 0, bytes.length); } @Override public void readFully(final byte[] bytes, final int offset, final int length) throws IOException { if (length < 0 || offset < 0 || offset + length > bytes.length) { throw new IndexOutOfBoundsException(); } if (pointer + length > size) { throw new EOFException(); } System.arraycopy(buffer, pointer, bytes, offset, length); pointer += length; } @Override public int skipBytes(final int n) throws IOException { seek(pointer + n); return n; } @Override public byte readByte() throws IOException { if (pointer >= size) { throw new EOFException(); } return buffer[pointer++]; } @Override public boolean readBoolean() throws IOException { return readByte() != 0; } @Override public int readUnsignedByte() throws IOException { if (pointer >= size) { throw new EOFException(); } return read(); } @Override public int readUnsignedShort() throws IOException { if (pointer + 2 > size) { throw new EOFException(); } return (read() << 8) + read(); } @Override public short readShort() throws IOException { return (short)readUnsignedShort(); } @Override public char readChar() throws IOException { return (char)readUnsignedShort(); } @Override public int readInt() throws IOException { if (pointer + 4 > size) { throw new EOFException(); } return (read() << 24) + (read() << 16) + (read() << 8) + read(); } @Override public long readLong() throws IOException { if (pointer + 8 > size) { throw new EOFException(); } - return (read() << 56) + - (read() << 48) + - (read() << 40) + - (read() << 32) + + return ((long)read() << 56) + + ((long)read() << 48) + + ((long)read() << 40) + + ((long)read() << 32) + (read() << 24) + (read() << 16) + (read() << 8) + read(); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } /** * This methods throws an {@link UnsupportedOperationException} because the method * is deprecated and not used in the context of this implementation. * * @deprecated Does not support UTF-8, use readUTF() instead */ @Override @Deprecated public String readLine() throws IOException { throw new UnsupportedOperationException("readLine() is deprecated and not supported"); } @Override public String readUTF() throws IOException { return DataInputStream.readUTF(this); } // private private int read() { return buffer[pointer++] & 0xff; } private void resizeIfNeeded() { if (size >= buffer.length) { final byte[] newBuffer = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } }
true
true
public long readLong() throws IOException { if (pointer + 8 > size) { throw new EOFException(); } return (read() << 56) + (read() << 48) + (read() << 40) + (read() << 32) + (read() << 24) + (read() << 16) + (read() << 8) + read(); }
public long readLong() throws IOException { if (pointer + 8 > size) { throw new EOFException(); } return ((long)read() << 56) + ((long)read() << 48) + ((long)read() << 40) + ((long)read() << 32) + (read() << 24) + (read() << 16) + (read() << 8) + read(); }
diff --git a/modules/axiom-tests/src/test/java/org/apache/axiom/soap/impl/llom/CharacterEncoding2Test.java b/modules/axiom-tests/src/test/java/org/apache/axiom/soap/impl/llom/CharacterEncoding2Test.java index 412742e89..3ab4699ca 100644 --- a/modules/axiom-tests/src/test/java/org/apache/axiom/soap/impl/llom/CharacterEncoding2Test.java +++ b/modules/axiom-tests/src/test/java/org/apache/axiom/soap/impl/llom/CharacterEncoding2Test.java @@ -1,50 +1,51 @@ package org.apache.axiom.soap.impl.llom; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder; import org.apache.axiom.om.OMOutputFormat; import org.custommonkey.xmlunit.XMLTestCase; import org.custommonkey.xmlunit.XMLUnit; import javax.xml.stream.XMLInputFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.io.InputStreamReader; public class CharacterEncoding2Test extends XMLTestCase { String xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + "<AgendaPesquisa>" + "<status>0</status>" + "<ListaContatosPesquisa>" + "<tipo>C</tipo>" + "<dono>lucia</dono>" + "<posicao>177</posicao>" + "<nome>Abric� Gimar�es</nome>" + "<email></email>" + "</ListaContatosPesquisa>" + "</AgendaPesquisa>" + "</soap:Body>" + "</soap:Envelope>"; public void testISO99591() throws Exception { ByteArrayInputStream byteInStr = new ByteArrayInputStream(xml.getBytes("iso-8859-1")); StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder( XMLInputFactory.newInstance().createXMLStreamReader(byteInStr)); SOAPEnvelope envelope = builder.getSOAPEnvelope(); envelope.build(); assertEquals("iso-8859-1", envelope.getXMLStreamReader().getCharacterEncodingScheme()); ByteArrayOutputStream byteOutStr = new ByteArrayOutputStream(); OMOutputFormat outputFormat = new OMOutputFormat(); outputFormat.setCharSetEncoding("iso-8859-1"); envelope.serialize(byteOutStr, outputFormat); - assertXMLEqual(new StringReader(xml), new InputStreamReader(new ByteArrayInputStream(byteOutStr.toByteArray()))); + assertXMLEqual(new InputStreamReader(new ByteArrayInputStream(xml.getBytes("iso-8859-1")),"iso-8859-1"), + new InputStreamReader(new ByteArrayInputStream(byteOutStr.toByteArray()),"iso-8859-1")); } }
true
true
public void testISO99591() throws Exception { ByteArrayInputStream byteInStr = new ByteArrayInputStream(xml.getBytes("iso-8859-1")); StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder( XMLInputFactory.newInstance().createXMLStreamReader(byteInStr)); SOAPEnvelope envelope = builder.getSOAPEnvelope(); envelope.build(); assertEquals("iso-8859-1", envelope.getXMLStreamReader().getCharacterEncodingScheme()); ByteArrayOutputStream byteOutStr = new ByteArrayOutputStream(); OMOutputFormat outputFormat = new OMOutputFormat(); outputFormat.setCharSetEncoding("iso-8859-1"); envelope.serialize(byteOutStr, outputFormat); assertXMLEqual(new StringReader(xml), new InputStreamReader(new ByteArrayInputStream(byteOutStr.toByteArray()))); }
public void testISO99591() throws Exception { ByteArrayInputStream byteInStr = new ByteArrayInputStream(xml.getBytes("iso-8859-1")); StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder( XMLInputFactory.newInstance().createXMLStreamReader(byteInStr)); SOAPEnvelope envelope = builder.getSOAPEnvelope(); envelope.build(); assertEquals("iso-8859-1", envelope.getXMLStreamReader().getCharacterEncodingScheme()); ByteArrayOutputStream byteOutStr = new ByteArrayOutputStream(); OMOutputFormat outputFormat = new OMOutputFormat(); outputFormat.setCharSetEncoding("iso-8859-1"); envelope.serialize(byteOutStr, outputFormat); assertXMLEqual(new InputStreamReader(new ByteArrayInputStream(xml.getBytes("iso-8859-1")),"iso-8859-1"), new InputStreamReader(new ByteArrayInputStream(byteOutStr.toByteArray()),"iso-8859-1")); }
diff --git a/src/me/greatman/Craftconomy/utils/DatabaseHandler.java b/src/me/greatman/Craftconomy/utils/DatabaseHandler.java index 92e084c..08bb36c 100644 --- a/src/me/greatman/Craftconomy/utils/DatabaseHandler.java +++ b/src/me/greatman/Craftconomy/utils/DatabaseHandler.java @@ -1,1166 +1,1166 @@ package me.greatman.Craftconomy.utils; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.bukkit.World; import com.sun.rowset.CachedRowSetImpl; import me.greatman.Craftconomy.Account; import me.greatman.Craftconomy.AccountHandler; import me.greatman.Craftconomy.Bank; import me.greatman.Craftconomy.Craftconomy; import me.greatman.Craftconomy.Currency; import me.greatman.Craftconomy.CurrencyHandler; import me.greatman.Craftconomy.ILogger; @SuppressWarnings("restriction") public class DatabaseHandler { private static SQLLibrary database = null; /** * Load the DatabaseHandler. Create the tables if needed * * @param thePlugin The Craftconomy plugin * @return Success to everything or false. */ public static boolean load(Craftconomy thePlugin) { if (Config.databaseType.equalsIgnoreCase("SQLite") || Config.databaseType.equalsIgnoreCase("minidb")) { database = new SQLLibrary("jdbc:sqlite:" + Craftconomy.plugin.getDataFolder().getAbsolutePath() + File.separator + "database.db","","", DatabaseType.SQLITE); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username VARCHAR(30) UNIQUE NOT NULL)", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "plural VARCHAR(30) NOT NULL," + "minor VARCHAR(30) NOT NULL," + "minorplural VARCHAR(30) NOT NULL)", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); e.printStackTrace(); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); //We check if it's the latest version ResultSet result; try { result = database.query("PRAGMA table_info(" + Config.databaseCurrencyTable + ")", true); if (result != null) { while(result.next()) { if (map.containsKey(result.getString("name"))) { map.put(result.getString("name"), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN plural VARCHAR(30)", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minor VARCHAR(30)", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minorplural VARCHAR(30)", false); - ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); + ILogger.info("Column minorplural added in " + Config.databaseCurrencyTable + " table"); } } } } catch (SQLException e) { e.printStackTrace(); } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "src VARCHAR ( 30 ) NOT NULL , " + "dest VARCHAR ( 30 ) NOT NULL , " + "rate DOUBLE NOT NULL)", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "owner VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "bank_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "bank_id INTEGER NOT NULL," + "playerName VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("SQLite database loaded!"); return true; } else if (Config.databaseType.equalsIgnoreCase("mysql")) { database = new SQLLibrary("jdbc:mysql://" + Config.databaseAddress + ":" + Config.databasePort + "/" + Config.databaseDb, Config.databaseUsername, Config.databasePassword, DatabaseType.MYSQL); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL, " + "`plural` VARCHAR( 30 ) NOT NULL, " + "`minor` VARCHAR( 30 ) NOT NULL, " + "`minorplural` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); ResultSet result; try { result = database.query("SHOW COLUMNS FROM " + Config.databaseCurrencyTable, true); while(result.next()) { if (map.containsKey(result.getString(1))) { map.put(result.getString(1), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD plural VARCHAR(30) NOT NULL", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minor VARCHAR(30) NOT NULL", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minorplural VARCHAR(30) NOT NULL", false); ILogger.info("Column minorplural added in " + Config.databaseCurrencyTable + " table"); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "`src` VARCHAR ( 30 ) NOT NULL , " + "`dest` VARCHAR ( 30 ) NOT NULL , " + "`rate` DOUBLE NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL , " + "`owner` VARCHAR( 30 ) NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`bank_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "`bank_id` INT NOT NULL ," + "`playerName` INT NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("MySQL table loaded!"); return true; } return false; } public static boolean exists(String account) { ResultSet result = null; boolean exists = false; String query = "SELECT * FROM " + Config.databaseAccountTable + " WHERE username='" + account + "'"; try { result = database.query(query, true); if (result.next()) exists = true; } catch (SQLException e) { } return exists; } public static void create(String accountName) { String query = "INSERT INTO " + Config.databaseAccountTable + "(username) VALUES('" + accountName + "')"; try { database.query(query, false); Account account = AccountHandler.getAccount(accountName); query = "INSERT INTO " + Config.databaseBalanceTable + "(username_id,worldName,currency_id,balance) VALUES(" + account.getPlayerId() + "," + "'" + Craftconomy.plugin.getServer().getWorlds().get(0).getName() + "'," + getCurrencyId(Config.currencyDefault) + "," + Config.defaultHoldings + ")"; database.query(query, false); } catch (SQLException e) { e.printStackTrace(); } } public static void deleteAll() { String query = "DELETE FROM " + Config.databaseAccountTable; try { database.query(query, false); query = "DELETE FROM " + Config.databaseBalanceTable; database.query(query, false); query = "DELETE FROM " + Config.databaseCurrencyTable; database.query(query, false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name) VALUES('" + Config.currencyDefault + "')", false); query = "DELETE FROM " + Config.databaseBankTable; database.query(query, false); query = "DELETE FROM " + Config.databaseBankBalanceTable; database.query(query, false); } catch (SQLException e) { e.printStackTrace(); } } public static void deleteAllInitialAccounts() { String query = "DELETE FROM " + Config.databaseAccountTable + " WHERE balance=" + Config.defaultHoldings; try { database.query(query, false); } catch (SQLException e) { e.printStackTrace(); } } public static ResultSet getAllInitialAccounts() { String query = "SELECT * FROM " + Config.databaseAccountTable + " WHERE balance=" + Config.defaultHoldings; try { return database.query(query, true); } catch (SQLException e) { e.printStackTrace(); } return null; } // TODO: Make that it verify if he is a bank owner public static void delete(String playerName) { String query = "DELETE FROM " + Config.databaseAccountTable + " WHERE username='" + playerName + "'"; try { int accountId = getAccountId(playerName); database.query(query, false); if (accountId != 0) { query = "DELETE FROM " + Config.databaseBalanceTable + " WHERE username_id=" + accountId; database.query(query, false); } } catch (SQLException e) { e.printStackTrace(); } } public static int getAccountId(String playerName) { int accountId = 0; try { ResultSet result = database.query("SELECT id FROM " + Config.databaseAccountTable + " WHERE username='" + playerName + "'", true); if (result != null) { result.next(); accountId = result.getInt("id"); } } catch (SQLException e) { e.printStackTrace(); } return accountId; } public static String getAccountNameById(int id) { String accountName = null; try { ResultSet result = database.query("SELECT username FROM " + Config.databaseAccountTable + " WHERE id=" + id, true); if (result != null) { result.next(); accountName = result.getString("username"); } } catch (SQLException e) { } return accountName; } /* * Update an account */ public static void updateAccount(Account account, double balance, Currency currency, World world) { String query = "SELECT id FROM " + Config.databaseBalanceTable + " WHERE " + "username_id=" + account.getPlayerId() + " AND worldName='" + world.getName() + "'" + " AND currency_id=" + currency.getdatabaseId(); CachedRowSetImpl result; try { result = database.query(query, true); if (result != null && result.size() != 0) { query = "UPDATE " + Config.databaseBalanceTable + " SET balance=" + balance + " WHERE username_id=" + account.getPlayerId() + " AND worldName='" + world.getName() + "'" + " AND currency_id=" + currency.getdatabaseId(); database.query(query, false); } else { query = "INSERT INTO " + Config.databaseBalanceTable + "(username_id,worldName,currency_id,balance) VALUES(" + account.getPlayerId() + "," + "'" + world.getName() + "'," + currency.getdatabaseId() + "," + balance + ")"; database.query(query, false); } } catch (SQLException e) { e.printStackTrace(); } } /* * Balance functions */ /** * Get the default balance (When not MultiWorld) * * @param account The account we want to get the default balance from. * @return The requested balance */ // public static double getDefaultBalance(Account account) // { // if (!Config.multiWorld) // return getDefaultBalance(account, // Craftconomy.plugin.getServer().getWorlds().get(0)); // return 0.00; // } /** * Get the default balance (When MultiWorld) * * @param account The account we want to get the default balance from * @param worldName The world name * @return the requested balance */ /* * public static double getDefaultBalance(Account account, World world) { * return getBalanceCurrency(account, world.getName(), * CurrencyHandler.getCurrency(Config.currencyDefault, true)); } */ /** * Grab all balance from a account (When not multiWorld) * * @param account The account we want to get the balance from * @return The result of the query or null if the system is MultiWorld * enabled */ public static ResultSet getAllBalance(Account account) { String query = "SELECT balance,currency_id,worldName,Currency.name FROM " + Config.databaseBalanceTable + " LEFT JOIN " + Config.databaseCurrencyTable + " ON " + Config.databaseBalanceTable + ".currency_id = " + Config.databaseCurrencyTable + ".id WHERE username_id=" + account.getPlayerId() + " ORDER BY worldName"; try { ResultSet result = database.query(query, true); if (result != null) { return result; } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Get the balance of a account * * @param account The account we want to get the balance * @param world The world that we want to check the balance * @param currency The currency we want to check * @return The balance */ public static double getBalanceCurrency(Account account, World world, Currency currency) { if (currency.getdatabaseId() != 0) { String query = "SELECT balance FROM " + Config.databaseBalanceTable + " WHERE username_id='" + account.getPlayerId() + "' AND worldName='" + world.getName() + "' AND currency_id=" + currency.getdatabaseId(); ResultSet result; try { result = database.query(query, true); if (result != null) { if (!result.isLast()) { result.next(); return result.getDouble("balance"); } } } catch (SQLException e) { e.printStackTrace(); } } return 0.00; } /* * Currency functions */ /** * Get the currency database ID * * @param currency The currency we want to get the ID * @return The Currency ID */ public static int getCurrencyId(String currency) { if (currencyExist(currency, true)) { String query = "SELECT id FROM " + Config.databaseCurrencyTable + " WHERE name='" + currency + "'"; ResultSet result; try { result = database.query(query, true); if (result != null) { result.next(); return result.getInt("id"); } } catch (SQLException e) { e.printStackTrace(); } } return 0; } /** * Verify if a currency exists in the database * * @param currency The currency name we want to check * @return True if the currency exists, else false */ public static boolean currencyExist(String currency) { return currencyExist(currency, false); } /** * Verify if a currency exist in the database * * @param currency The currency we want to check * @param exact If we give the exact name or not * @return True if the currency exists, else false. */ public static boolean currencyExist(String currency, boolean exact) { String query; if (exact) query = "SELECT * FROM " + Config.databaseCurrencyTable + " WHERE name='" + currency + "'"; else query = "SELECT * FROM " + Config.databaseCurrencyTable + " WHERE name LIKE '%" + currency + "%'"; try { CachedRowSetImpl result = database.query(query, true); if (result != null) { if (result.size() == 1) { return true; } } } catch (SQLException e) { e.printStackTrace(); } return false; } // TODO: ??????????????????????? /** * Get the Currency full name * * @param currencyName The currency name we want to get * @param exact If we give the exact name or not * @return The currency name */ public static String getCurrencyName(String currencyName, boolean exact) { String query; if (exact) query = "SELECT name FROM " + Config.databaseCurrencyTable + " WHERE name='" + currencyName + "'"; else query = "SELECT name FROM " + Config.databaseCurrencyTable + " WHERE name LIKE '%" + currencyName + "%'"; ResultSet result; try { result = database.query(query, true); if (result != null) { result.next(); return result.getString("name"); } } catch (SQLException e) { e.printStackTrace(); } return null; } public static boolean createCurrency(String currencyName, String currencyNamePlural, String currencyMinor, String currencyMinorPlural) { boolean success = false; if (!currencyExist(currencyName, true)) { String query = "INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + currencyName + "'," + "'" + currencyNamePlural + "'," + "'" + currencyMinor + "'," + "'" + currencyMinorPlural + "',)"; try { database.query(query, false); success = true; } catch (SQLException e) { e.printStackTrace(); } } return success; } public static boolean modifyCurrency(CurrencyHandler.editType type, String oldCurrencyName, String newCurrencyName) { boolean success = false; if (currencyExist(oldCurrencyName, true)) { String query = ""; if (type == CurrencyHandler.editType.NAME) { CurrencyHandler.getCurrency(oldCurrencyName, true).setName(newCurrencyName); query = "UPDATE " + Config.databaseCurrencyTable + " SET name='" + newCurrencyName + "' WHERE name='" + oldCurrencyName + "'"; } else if (type == CurrencyHandler.editType.PLURAL) { CurrencyHandler.getCurrency(oldCurrencyName, true).setNamePlural(newCurrencyName); query = "UPDATE " + Config.databaseCurrencyTable + " SET plural='" + newCurrencyName + "' WHERE name='" + oldCurrencyName + "'"; } else if (type == CurrencyHandler.editType.MINOR) { CurrencyHandler.getCurrency(oldCurrencyName, true).setNameMinor(newCurrencyName); query = "UPDATE " + Config.databaseCurrencyTable + " SET minor='" + newCurrencyName + "' WHERE name='" + oldCurrencyName + "'"; } else if (type == CurrencyHandler.editType.MINORPLURAL) { CurrencyHandler.getCurrency(oldCurrencyName, true).setNameMinorPlural(newCurrencyName); query = "UPDATE " + Config.databaseCurrencyTable + " SET minorplural='" + newCurrencyName + "' WHERE name='" + oldCurrencyName + "'"; } try { database.query(query, false); success = true; } catch (SQLException e) { e.printStackTrace(); } } return success; } public static boolean removeCurrency(String currencyName) { boolean success = false; if (currencyExist(currencyName, true)) { String query2 = "DELETE FROM " + Config.databaseBalanceTable + " WHERE currency_id=" + getCurrencyId(currencyName); String query = "DELETE FROM " + Config.databaseCurrencyTable + " WHERE name='" + currencyName + "'"; try { database.query(query, false); database.query(query2, false); success = true; } catch (SQLException e) { e.printStackTrace(); } } return success; } public static boolean bankExists(String bankName) { String query = "SELECT * FROM " + Config.databaseBankTable + " WHERE name='" + bankName + "'"; try { CachedRowSetImpl result = database.query(query, true); if (result != null) { if (result.size() == 1) return true; else return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } public static void updateBankAccount(Bank bank, double balance, Currency currency, World world) { String query = "SELECT id FROM " + Config.databaseBankBalanceTable + " WHERE " + "bank_id=" + bank.getId() + " AND worldName='" + world.getName() + "'" + " AND currency_id=" + currency.getdatabaseId(); CachedRowSetImpl result; try { result = database.query(query, true); if (result != null && result.size() != 0) { query = "UPDATE " + Config.databaseBankBalanceTable + " SET balance=" + balance + " WHERE bank_id=" + bank.getId() + " AND worldName='" + world.getName() + "'" + " AND currency_id=" + currency.getdatabaseId(); database.query(query, false); } else { query = "INSERT INTO " + Config.databaseBankBalanceTable + "(bank_id,worldName,currency_id,balance) VALUES(" + bank.getId() + "," + "'" + world.getName() + "'," + currency.getdatabaseId() + "," + balance + ")"; database.query(query, false); } } catch (SQLException e) { e.printStackTrace(); } } public static String getBankOwner(String bankName) { if (bankExists(bankName)) { String query = "SELECT owner FROM " + Config.databaseBankTable + " WHERE name='" + bankName + "'"; try { ResultSet result = database.query(query, true); if (result != null) { result.next(); return result.getString("owner"); } } catch (SQLException e) { e.printStackTrace(); } } return null; } public static double getBankBalanceCurrency(Bank bank, World world, Currency currency) { if (bankExists(bank.getName())) { String query = "SELECT balance FROM " + Config.databaseBankBalanceTable + " WHERE bank_id='" + bank.getId() + "' AND worldName='" + world.getName() + "' AND currency_id=" + currency.getdatabaseId(); ResultSet result; try { result = database.query(query, true); if (result != null) { if (!result.isLast()) { result.next(); return result.getDouble("balance"); } } } catch (SQLException e) { e.printStackTrace(); } } return 0.00; } public static int getBankId(String bankName) { String query = "SELECT id FROM " + Config.databaseBankTable + " WHERE name='" + bankName + "'"; try { ResultSet result = database.query(query, true); if (result != null) { if (!result.isLast()) { result.next(); return result.getInt("id"); } } } catch (SQLException e) { e.printStackTrace(); } return 0; } public static boolean createBank(String bankName, String playerName) { boolean result = false; String query = "INSERT INTO " + Config.databaseBankTable + "(name,owner) VALUES('" + bankName + "','" + playerName + "')"; try { database.query(query, false); result = true; } catch (SQLException e) { e.printStackTrace(); } return result; } public static boolean deleteBank(String bankName) { boolean result = false; if (bankExists(bankName)) { String query = "DELETE FROM " + Config.databaseBankTable + " WHERE name='" + bankName + "'"; try { database.query(query, false); result = true; } catch (SQLException e) { e.printStackTrace(); } } return result; } public static ResultSet getAllBankBalance(Bank bank) { String query = "SELECT balance,currency_id,worldName,Currency.name FROM " + Config.databaseBankBalanceTable + " LEFT JOIN " + Config.databaseCurrencyTable + " ON " + Config.databaseBankBalanceTable + ".currency_id = " + Config.databaseCurrencyTable + ".id WHERE bank_id=" + bank.getId() + " ORDER BY worldName"; try { ResultSet result = database.query(query, true); if (result != null) { return result; } } catch (SQLException e) { e.printStackTrace(); } return null; } public static List<String> getBankMembers(Bank bank) { String query = "SELECT * FROM " + Config.databaseBankMemberTable + " WHERE bank_id = " + bank.getId(); List<String> list = new ArrayList<String>(); try { ResultSet result = database.query(query, true); if (result != null) { while (result.next()) { list.add(result.getString("playerName")); } return list; } } catch (SQLException e) { e.printStackTrace(); } return null; } public static List<String> listBanks() { String query = "SELECT name FROM " + Config.databaseBankTable; List<String> list = new ArrayList<String>(); try { ResultSet result = database.query(query, true); if (result != null) { while (result.next()) { list.add(result.getString("name")); } return list; } } catch (SQLException e) { e.printStackTrace(); } return null; } public static void addBankMember(Bank bank, String playerName) { String query = "INSERT INTO " + Config.databaseBankMemberTable + " VALUES(" + bank.getId() + ",'" + playerName + "')"; try { database.query(query, false); } catch (SQLException e) { e.printStackTrace(); } } public static void removeBankMember(Bank bank, String playerName) { String query = "DELETE FROM " + Config.databaseBankMemberTable + " WHERE bank_id=" + bank.getId() + " AND playerName='" + playerName + "'"; try { database.query(query, false); } catch (SQLException e) { e.printStackTrace(); } } public static void setExchangeRate(Currency src, Currency dest, double rate) { // already in? String query = "SELECT * FROM " + Config.databaseCurrencyExchangeTable + " WHERE src = '" + src.getName() + "' AND dest = '" + dest.getName() + "'"; try { ResultSet result = database.query(query, true); if (result.next()) { query = "UPDATE " + Config.databaseCurrencyExchangeTable + " SET rate=" + rate + " WHERE src='" + src.getName() + "' AND dest = '" + dest.getName() + "'"; database.query(query, false); } else { // create new query = "INSERT INTO " + Config.databaseCurrencyExchangeTable + " (src, dest, rate) VALUES ('" + src.getName() + "','" + dest.getName() + "'," + String.valueOf(rate) + ")"; database.query(query, false); } } catch (SQLException e) { e.printStackTrace(); } } public static HashMap<String, Double> getExchangeRates(Currency a) { String query = "SELECT * FROM " + Config.databaseCurrencyExchangeTable + " WHERE src = '" + a.getName() + "'"; HashMap<String, Double> ret = new HashMap<String, Double>(); try { ResultSet result = database.query(query, true); if (result != null) { while (result.next()) { ret.put(result.getString("dest"), result.getDouble("rate")); } } } catch (SQLException e) { e.printStackTrace(); } return ret; } public static HashMap<String,String> getCurrencyNames(String currencyName, boolean exact) { HashMap<String,String> map = new HashMap<String,String>(); String query; if (exact) query = "SELECT * FROM " + Config.databaseCurrencyTable + " WHERE name='" + currencyName + "'"; else query = "SELECT * FROM " + Config.databaseCurrencyTable + " WHERE name LIKE '%" + currencyName + "%'"; ResultSet result; try { result = database.query(query, true); if (result != null) { result.next(); map.put("name", result.getString("name")); map.put("plural", result.getString("plural")); map.put("minor", result.getString("minor")); map.put("minorplural", result.getString("minorplural")); return map; } } catch (SQLException e) { e.printStackTrace(); } return null; } public static List<Account> getTopList(Currency source, World world) { String query = "SELECT * FROM " + Config.databaseBalanceTable +"" + " LEFT JOIN " + Config.databaseAccountTable + " ON " + Config.databaseBalanceTable + ".username_id = " + Config.databaseAccountTable + ".id WHERE currency_id=" + source.getdatabaseId() + " AND worldName='" + world.getName() + "' ORDER BY balance DESC" ; List<Account> accountList = new ArrayList<Account>(); try{ ResultSet result = database.query(query,true); if (result != null) { int i = 0; while(result.next() && i < 10) { accountList.add(AccountHandler.getAccount(result.getString("username"))); i++; } } } catch (SQLException e) { e.printStackTrace(); } return accountList; } }
true
true
public static boolean load(Craftconomy thePlugin) { if (Config.databaseType.equalsIgnoreCase("SQLite") || Config.databaseType.equalsIgnoreCase("minidb")) { database = new SQLLibrary("jdbc:sqlite:" + Craftconomy.plugin.getDataFolder().getAbsolutePath() + File.separator + "database.db","","", DatabaseType.SQLITE); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username VARCHAR(30) UNIQUE NOT NULL)", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "plural VARCHAR(30) NOT NULL," + "minor VARCHAR(30) NOT NULL," + "minorplural VARCHAR(30) NOT NULL)", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); e.printStackTrace(); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); //We check if it's the latest version ResultSet result; try { result = database.query("PRAGMA table_info(" + Config.databaseCurrencyTable + ")", true); if (result != null) { while(result.next()) { if (map.containsKey(result.getString("name"))) { map.put(result.getString("name"), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN plural VARCHAR(30)", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minor VARCHAR(30)", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minorplural VARCHAR(30)", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } } } } catch (SQLException e) { e.printStackTrace(); } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "src VARCHAR ( 30 ) NOT NULL , " + "dest VARCHAR ( 30 ) NOT NULL , " + "rate DOUBLE NOT NULL)", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "owner VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "bank_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "bank_id INTEGER NOT NULL," + "playerName VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("SQLite database loaded!"); return true; } else if (Config.databaseType.equalsIgnoreCase("mysql")) { database = new SQLLibrary("jdbc:mysql://" + Config.databaseAddress + ":" + Config.databasePort + "/" + Config.databaseDb, Config.databaseUsername, Config.databasePassword, DatabaseType.MYSQL); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL, " + "`plural` VARCHAR( 30 ) NOT NULL, " + "`minor` VARCHAR( 30 ) NOT NULL, " + "`minorplural` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); ResultSet result; try { result = database.query("SHOW COLUMNS FROM " + Config.databaseCurrencyTable, true); while(result.next()) { if (map.containsKey(result.getString(1))) { map.put(result.getString(1), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD plural VARCHAR(30) NOT NULL", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minor VARCHAR(30) NOT NULL", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minorplural VARCHAR(30) NOT NULL", false); ILogger.info("Column minorplural added in " + Config.databaseCurrencyTable + " table"); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "`src` VARCHAR ( 30 ) NOT NULL , " + "`dest` VARCHAR ( 30 ) NOT NULL , " + "`rate` DOUBLE NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL , " + "`owner` VARCHAR( 30 ) NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`bank_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "`bank_id` INT NOT NULL ," + "`playerName` INT NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("MySQL table loaded!"); return true; } return false; }
public static boolean load(Craftconomy thePlugin) { if (Config.databaseType.equalsIgnoreCase("SQLite") || Config.databaseType.equalsIgnoreCase("minidb")) { database = new SQLLibrary("jdbc:sqlite:" + Craftconomy.plugin.getDataFolder().getAbsolutePath() + File.separator + "database.db","","", DatabaseType.SQLITE); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username VARCHAR(30) UNIQUE NOT NULL)", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "plural VARCHAR(30) NOT NULL," + "minor VARCHAR(30) NOT NULL," + "minorplural VARCHAR(30) NOT NULL)", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); e.printStackTrace(); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); //We check if it's the latest version ResultSet result; try { result = database.query("PRAGMA table_info(" + Config.databaseCurrencyTable + ")", true); if (result != null) { while(result.next()) { if (map.containsKey(result.getString("name"))) { map.put(result.getString("name"), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN plural VARCHAR(30)", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minor VARCHAR(30)", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD COLUMN minorplural VARCHAR(30)", false); ILogger.info("Column minorplural added in " + Config.databaseCurrencyTable + " table"); } } } } catch (SQLException e) { e.printStackTrace(); } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "src VARCHAR ( 30 ) NOT NULL , " + "dest VARCHAR ( 30 ) NOT NULL , " + "rate DOUBLE NOT NULL)", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "username_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(30) UNIQUE NOT NULL," + "owner VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " (" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "bank_id INTEGER NOT NULL," + "currency_id INTEGER NOT NULL," + "worldName VARCHAR(30) NOT NULL," + "balance DOUBLE NOT NULL)", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "bank_id INTEGER NOT NULL," + "playerName VARCHAR(30) NOT NULL)", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("SQLite database loaded!"); return true; } else if (Config.databaseType.equalsIgnoreCase("mysql")) { database = new SQLLibrary("jdbc:mysql://" + Config.databaseAddress + ":" + Config.databasePort + "/" + Config.databaseDb, Config.databaseUsername, Config.databasePassword, DatabaseType.MYSQL); if (!database.checkTable(Config.databaseAccountTable)) { try { database.query("CREATE TABLE " + Config.databaseAccountTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseAccountTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseAccountTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`username_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseCurrencyTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL, " + "`plural` VARCHAR( 30 ) NOT NULL, " + "`minor` VARCHAR( 30 ) NOT NULL, " + "`minorplural` VARCHAR( 30 ) NOT NULL " + ") ENGINE = InnoDB;", false); database.query("INSERT INTO " + Config.databaseCurrencyTable + "(name,plural,minor,minorplural) VALUES(" + "'" + Config.currencyDefault + "'," + "'" + Config.currencyDefaultPlural + "'," + "'" + Config.currencyDefaultMinor + "'," + "'" + Config.currencyDefaultMinorPlural + "')", false); ILogger.info(Config.databaseCurrencyTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyTable + " table!"); return false; } } else { HashMap<String,Boolean> map = new HashMap<String,Boolean>(); map.put("plural", false); map.put("minor", false); map.put("minorplural", false); ResultSet result; try { result = database.query("SHOW COLUMNS FROM " + Config.databaseCurrencyTable, true); while(result.next()) { if (map.containsKey(result.getString(1))) { map.put(result.getString(1), true); } } if (map.containsValue(false)) { ILogger.info("Updating " + Config.databaseCurrencyTable + " table"); if (!map.get("plural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD plural VARCHAR(30) NOT NULL", false); ILogger.info("Column plural added in " + Config.databaseCurrencyTable + " table"); } if (!map.get("minor")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minor VARCHAR(30) NOT NULL", false); ILogger.info("Column minor added in " + Config.databaseCurrencyTable + " table"); } if(!map.get("minorplural")) { database.query("ALTER TABLE " + Config.databaseCurrencyTable + " ADD minorplural VARCHAR(30) NOT NULL", false); ILogger.info("Column minorplural added in " + Config.databaseCurrencyTable + " table"); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } if (!database.checkTable(Config.databaseCurrencyExchangeTable)) { try { database.query("CREATE TABLE " + Config.databaseCurrencyExchangeTable + " ( " + "`src` VARCHAR ( 30 ) NOT NULL , " + "`dest` VARCHAR ( 30 ) NOT NULL , " + "`rate` DOUBLE NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseCurrencyExchangeTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseCurrencyExchangeTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankTable)) { try { database.query("CREATE TABLE " + Config.databaseBankTable + " (" + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , " + "`name` VARCHAR( 30 ) NOT NULL , " + "`owner` VARCHAR( 30 ) NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankBalanceTable)) { try { database.query("CREATE TABLE " + Config.databaseBankBalanceTable + " ( " + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," + "`bank_id` INT NOT NULL ," + "`currency_id` INT NOT NULL , " + "`worldName` VARCHAR( 30 ) NOT NULL , " + "`balance` DOUBLE NOT NULL) ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankBalanceTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankBalanceTable + " table!"); return false; } } if (!database.checkTable(Config.databaseBankMemberTable)) { try { database.query("CREATE TABLE " + Config.databaseBankMemberTable + " (" + "`bank_id` INT NOT NULL ," + "`playerName` INT NOT NULL " + ") ENGINE = InnoDB;", false); ILogger.info(Config.databaseBankMemberTable + " table created!"); } catch (SQLException e) { ILogger.error("Unable to create the " + Config.databaseBankMemberTable + " table!"); return false; } } ILogger.info("MySQL table loaded!"); return true; } return false; }
diff --git a/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/FlattenedCellSetFormatter.java b/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/FlattenedCellSetFormatter.java index 60e6d21f..383054da 100644 --- a/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/FlattenedCellSetFormatter.java +++ b/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/FlattenedCellSetFormatter.java @@ -1,566 +1,564 @@ /* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.saiku.olap.util.formatter; import org.olap4j.Cell; import org.olap4j.CellSet; import org.olap4j.CellSetAxis; import org.olap4j.Position; import org.olap4j.impl.CoordinateIterator; import org.olap4j.impl.Olap4jUtil; import org.olap4j.metadata.Dimension; import org.olap4j.metadata.Level; import org.olap4j.metadata.Member; import org.olap4j.metadata.Property; import org.saiku.olap.dto.resultset.DataCell; import org.saiku.olap.dto.resultset.Matrix; import org.saiku.olap.dto.resultset.MemberCell; import org.saiku.olap.util.SaikuProperties; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.*; public class FlattenedCellSetFormatter implements ICellSetFormatter { /** * Description of an axis. */ private static class AxisInfo { final List<AxisOrdinalInfo> ordinalInfos; /** * Creates an AxisInfo. * * @param ordinalCount * Number of hierarchies on this axis */ AxisInfo(final int ordinalCount) { ordinalInfos = new ArrayList<AxisOrdinalInfo>(ordinalCount); for (int i = 0; i < ordinalCount; i++) { ordinalInfos.add(new AxisOrdinalInfo()); } } /** * Returns the number of matrix columns required by this axis. The sum of the width of the hierarchies on this * axis. * * @return Width of axis */ public int getWidth() { int width = 0; for (final AxisOrdinalInfo info : ordinalInfos) { width += info.getWidth(); } return width; } } /** * Description of a particular hierarchy mapped to an axis. */ private static class AxisOrdinalInfo { private List<Integer> depths = new ArrayList<Integer>(); private Map<Integer,Level> depthLevel = new HashMap<Integer,Level>(); public int getWidth() { return depths.size(); } public List<Integer> getDepths() { return depths; } public Level getLevel(Integer depth) { return depthLevel.get(depth); } public void addLevel(Integer depth, Level level) { depthLevel.put(depth, level); } } /** * Returns an iterator over cells in a result. */ private static Iterable<Cell> cellIter(final int[] pageCoords, final CellSet cellSet) { return new Iterable<Cell>() { public Iterator<Cell> iterator() { final int[] axisDimensions = new int[cellSet.getAxes().size() - pageCoords.length]; assert pageCoords.length <= axisDimensions.length; for (int i = 0; i < axisDimensions.length; i++) { final CellSetAxis axis = cellSet.getAxes().get(i); axisDimensions[i] = axis.getPositions().size(); } final CoordinateIterator coordIter = new CoordinateIterator(axisDimensions, true); return new Iterator<Cell>() { public boolean hasNext() { return coordIter.hasNext(); } public Cell next() { final int[] ints = coordIter.next(); final AbstractList<Integer> intList = new AbstractList<Integer>() { @Override public Integer get(final int index) { return index < ints.length ? ints[index] : pageCoords[index - ints.length]; } @Override public int size() { return pageCoords.length + ints.length; } }; return cellSet.getCell(intList); } public void remove() { throw new UnsupportedOperationException(); } }; } }; } private Matrix matrix; private List<Integer> ignorex = new ArrayList<Integer>(); private List<Integer> ignorey = new ArrayList<Integer>(); public Matrix format(final CellSet cellSet) { // Compute how many rows are required to display the columns axis. final CellSetAxis columnsAxis; if (cellSet.getAxes().size() > 0) { columnsAxis = cellSet.getAxes().get(0); } else { columnsAxis = null; } final AxisInfo columnsAxisInfo = computeAxisInfo(columnsAxis); // Compute how many columns are required to display the rows axis. final CellSetAxis rowsAxis; if (cellSet.getAxes().size() > 1) { rowsAxis = cellSet.getAxes().get(1); } else { rowsAxis = null; } final AxisInfo rowsAxisInfo = computeAxisInfo(rowsAxis); if (cellSet.getAxes().size() > 2) { final int[] dimensions = new int[cellSet.getAxes().size() - 2]; for (int i = 2; i < cellSet.getAxes().size(); i++) { final CellSetAxis cellSetAxis = cellSet.getAxes().get(i); dimensions[i - 2] = cellSetAxis.getPositions().size(); } for (final int[] pageCoords : CoordinateIterator.iterate(dimensions)) { matrix = formatPage(cellSet, pageCoords, columnsAxis, columnsAxisInfo, rowsAxis, rowsAxisInfo); } } else { matrix = formatPage(cellSet, new int[] {}, columnsAxis, columnsAxisInfo, rowsAxis, rowsAxisInfo); } return matrix; } /** * Computes a description of an axis. * * @param axis * Axis * @return Description of axis */ private AxisInfo computeAxisInfo(final CellSetAxis axis) { if (axis == null) { return new AxisInfo(0); } final AxisInfo axisInfo = new AxisInfo(axis.getAxisMetaData().getHierarchies().size()); int p = -1; for (final Position position : axis.getPositions()) { ++p; int k = -1; for (final Member member : position.getMembers()) { ++k; final AxisOrdinalInfo axisOrdinalInfo = axisInfo.ordinalInfos.get(k); if (!axisOrdinalInfo.getDepths().contains(member.getDepth())) { axisOrdinalInfo.getDepths().add(member.getDepth()); axisOrdinalInfo.addLevel(member.getDepth(), member.getLevel()); Collections.sort(axisOrdinalInfo.depths); } } } return axisInfo; } /** * Formats a two-dimensional page. * * @param cellSet * Cell set * @param pageCoords * Print writer * @param pageCoords * Coordinates of page [page, chapter, section, ...] * @param columnsAxis * Columns axis * @param columnsAxisInfo * Description of columns axis * @param rowsAxis * Rows axis * @param rowsAxisInfo * Description of rows axis */ private Matrix formatPage(final CellSet cellSet, final int[] pageCoords, final CellSetAxis columnsAxis, final AxisInfo columnsAxisInfo, final CellSetAxis rowsAxis, final AxisInfo rowsAxisInfo) { // Figure out the dimensions of the blank rectangle in the top left // corner. final int yOffset = columnsAxisInfo.getWidth(); final int xOffsset = rowsAxisInfo.getWidth(); // Populate a string matrix final Matrix matrix = new Matrix(xOffsset + (columnsAxis == null ? 1 : columnsAxis.getPositions().size()), yOffset + (rowsAxis == null ? 1 : rowsAxis.getPositions().size())); // Populate corner List<Level> levels = new ArrayList<Level>(); if (rowsAxis != null && rowsAxis.getPositions().size() > 0) { Position p = rowsAxis.getPositions().get(0); for (int m = 0; m < p.getMembers().size(); m++) { AxisOrdinalInfo a = rowsAxisInfo.ordinalInfos.get(m); for (Integer depth : a.getDepths()) { levels.add(a.getLevel(depth)); } } for (int x = 0; x < xOffsset; x++) { Level xLevel = levels.get(x); String s = xLevel.getCaption(); for (int y = 0; y < yOffset; y++) { final MemberCell memberInfo = new MemberCell(false, x > 0); if (y == yOffset-1) { memberInfo.setRawValue(s); memberInfo.setFormattedValue(s); memberInfo.setProperty("__headertype", "row_header_header"); memberInfo.setProperty("levelindex", "" + levels.indexOf(xLevel)); memberInfo.setHierarchy(xLevel.getHierarchy().getUniqueName()); memberInfo.setParentDimension(xLevel.getDimension().getName()); memberInfo.setLevel(xLevel.getUniqueName()); } matrix.set(x, y, memberInfo); } } } // Populate matrix with cells representing axes populateAxis(matrix, columnsAxis, columnsAxisInfo, true, xOffsset); populateAxis(matrix, rowsAxis, rowsAxisInfo, false, yOffset); int headerwidth = matrix.getMatrixWidth(); for(int yy=matrix.getMatrixHeight(); yy > matrix.getOffset() ; yy--) { for(int xx=0; xx < headerwidth-1;xx++) { if (matrix.get(xx,yy-1) != null && matrix.get(xx,yy) != null && matrix.get(xx,yy-1).getRawValue().equals(matrix.get(xx, yy).getRawValue())) { matrix.set(xx, yy, new MemberCell()); } else { break; } } } // Populate cell values int newyOffset = yOffset; int newxOffset = xOffsset; List<Integer> donex = new ArrayList<Integer>(); List<Integer> doney = new ArrayList<Integer>(); for (final Cell cell : cellIter(pageCoords, cellSet)) { final List<Integer> coordList = cell.getCoordinateList(); int y = newyOffset; int x = newxOffset; if (coordList.size() > 0) { if (coordList.get(0) == 0) { newxOffset = xOffsset; donex = new ArrayList<Integer>(); } x = newxOffset; if (coordList.size() > 0) x += coordList.get(0); y = newyOffset; if (coordList.size() > 1) y += coordList.get(1); boolean stop = false; if (coordList.size() > 0 && ignorex.contains(coordList.get(0))) { if (!donex.contains(coordList.get(0))) { newxOffset--; donex.add(coordList.get(0)); } stop = true; } if (coordList.size() > 1 && ignorey.contains(coordList.get(1))) { if (!doney.contains(coordList.get(1))) { newyOffset--; doney.add(coordList.get(1)); } stop = true; } if (stop) { continue; } } final DataCell cellInfo = new DataCell(true, false, coordList); cellInfo.setCoordinates(cell.getCoordinateList()); if (cell.getValue() != null) { try { cellInfo.setRawNumber(cell.getDoubleValue()); } catch (Exception e1) { } } String cellValue = cell.getFormattedValue(); // First try to get a // formatted value if (cellValue == null || cellValue.equals("null")) { //$NON-NLS-1$ cellValue =""; //$NON-NLS-1$ } if ( cellValue.length() < 1) { final Object value = cell.getValue(); if (value == null || value.equals("null")) //$NON-NLS-1$ cellValue = ""; //$NON-NLS-1$ else { try { // TODO this needs to become query / execution specific DecimalFormat myFormatter = new DecimalFormat(SaikuProperties.formatDefautNumberFormat); //$NON-NLS-1$ DecimalFormatSymbols dfs = new DecimalFormatSymbols(SaikuProperties.locale); myFormatter.setDecimalFormatSymbols(dfs); String output = myFormatter.format(cell.getValue()); cellValue = output; } catch (Exception e) { // TODO: handle exception } } // the raw value } // Format string is relevant for Excel export // xmla cells can throw an error on this try { String formatString = (String) cell.getPropertyValue(Property.StandardCellProperty.FORMAT_STRING); if (formatString != null && !formatString.startsWith("|")) { cellInfo.setFormatString(formatString); } else { formatString = formatString.substring(1, formatString.length()); cellInfo.setFormatString(formatString.substring(0, formatString.indexOf("|"))); } } catch (Exception e) { // we tried } Map<String, String> cellProperties = new HashMap<String, String>(); String val = Olap4jUtil.parseFormattedCellValue(cellValue, cellProperties); if (!cellProperties.isEmpty()) { cellInfo.setProperties(cellProperties); } cellInfo.setFormattedValue(val); matrix.set(x, y, cellInfo); } return matrix; } /** * Populates cells in the matrix corresponding to a particular axis. * * @param matrix * Matrix to populate * @param axis * Axis * @param axisInfo * Description of axis * @param isColumns * True if columns, false if rows * @param oldoffset * Ordinal of first cell to populate in matrix */ private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo, final boolean isColumns, final int oldoffset) { int offset = oldoffset; if (axis == null) return; final Member[] prevMembers = new Member[axisInfo.getWidth()]; final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()]; final Member[] members = new Member[axisInfo.getWidth()]; for (int i = 0; i < axis.getPositions().size(); i++) { final int x = offset + i; final Position position = axis.getPositions().get(i); int yOffset = 0; final List<Member> memberList = position.getMembers(); - final Map<Dimension,List<Integer>> lvls = new HashMap<Dimension, List<Integer>>(); boolean stop = false; for (int j = 0; j < memberList.size(); j++) { Member member = memberList.get(j); final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j); List<Integer> depths = ordinalInfo.depths; Collections.sort(depths); - lvls.put(member.getDimension(), depths); if (member.getDepth() < Collections.max(depths)) { stop = true; if (isColumns) { ignorex.add(i); } else { ignorey.add(i); } - continue; + break; } if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0)) break; final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth()); members[y] = member; yOffset += ordinalInfo.getWidth(); } if (stop) { offset--; continue; } boolean expanded = false; boolean same = true; for (int y = 0; y < members.length; y++) { final MemberCell memberInfo = new MemberCell(); final Member member = members[y]; int index = memberList.indexOf(member); if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); if (depth_i > 0) { expanded = true; } } memberInfo.setExpanded(expanded); same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member); if (member != null) { if (x - 1 == offset) memberInfo.setLastRow(true); matrix.setOffset(oldoffset); memberInfo.setRawValue(member.getCaption()); memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value memberInfo.setParentDimension(member.getDimension().getName()); memberInfo.setUniquename(member.getUniqueName()); memberInfo.setHierarchy(member.getHierarchy().getUniqueName()); memberInfo.setLevel(member.getLevel().getUniqueName()); // try { // memberInfo.setChildMemberCount(member.getChildMemberCount()); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // NamedList<Property> values = member.getLevel().getProperties(); // for(int j=0; j<values.size();j++){ // String val; // try { // val = member.getPropertyFormattedValue(values.get(j)); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // memberInfo.setProperty(values.get(j).getCaption(), val); // } // if (y > 0) { // for (int previ = y-1; previ >= 0;previ--) { // if(prevMembers[previ] != null) { // memberInfo.setRightOf(prevMemberInfo[previ]); // memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName()); // previ = -1; // } // } // } // if (member.getParentMember() != null) // memberInfo.setParentMember(member.getParentMember().getUniqueName()); } else { memberInfo.setRawValue(null); memberInfo.setFormattedValue(null); memberInfo.setParentDimension(null); } if (isColumns) { memberInfo.setRight(false); memberInfo.setSameAsPrev(same); if (member != null) memberInfo.setParentDimension(member.getDimension().getName()); matrix.set(x, y, memberInfo); } else { memberInfo.setRight(false); memberInfo.setSameAsPrev(false); matrix.set(y, x, memberInfo); } int x_parent = isColumns ? x : y-1; int y_parent = isColumns ? y-1 : x; if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); while (depth_i > 0) { depth_i--; int parentDepth = (ordinalInfo.getDepths().get(depth_i)); Member parent = member.getParentMember(); while (parent != null && parent.getDepth() > parentDepth) { parent = parent.getParentMember(); } final MemberCell pInfo = new MemberCell(); if (parent != null) { pInfo.setRawValue(parent.getCaption()); pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value pInfo.setParentDimension(parent.getDimension().getName()); pInfo.setHierarchy(parent.getHierarchy().getUniqueName()); pInfo.setUniquename(parent.getUniqueName()); pInfo.setLevel(parent.getLevel().getUniqueName()); } else { pInfo.setRawValue(""); pInfo.setFormattedValue(""); // First try to get a formatted value pInfo.setParentDimension(member.getDimension().getName()); pInfo.setHierarchy(member.getHierarchy().getUniqueName()); pInfo.setLevel(member.getLevel().getUniqueName()); pInfo.setUniquename(""); } matrix.set(x_parent, y_parent, pInfo); if (isColumns) { y_parent--; } else { x_parent--; } } } prevMembers[y] = member; prevMemberInfo[y] = memberInfo; members[y] = null; } } } }
false
true
private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo, final boolean isColumns, final int oldoffset) { int offset = oldoffset; if (axis == null) return; final Member[] prevMembers = new Member[axisInfo.getWidth()]; final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()]; final Member[] members = new Member[axisInfo.getWidth()]; for (int i = 0; i < axis.getPositions().size(); i++) { final int x = offset + i; final Position position = axis.getPositions().get(i); int yOffset = 0; final List<Member> memberList = position.getMembers(); final Map<Dimension,List<Integer>> lvls = new HashMap<Dimension, List<Integer>>(); boolean stop = false; for (int j = 0; j < memberList.size(); j++) { Member member = memberList.get(j); final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j); List<Integer> depths = ordinalInfo.depths; Collections.sort(depths); lvls.put(member.getDimension(), depths); if (member.getDepth() < Collections.max(depths)) { stop = true; if (isColumns) { ignorex.add(i); } else { ignorey.add(i); } continue; } if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0)) break; final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth()); members[y] = member; yOffset += ordinalInfo.getWidth(); } if (stop) { offset--; continue; } boolean expanded = false; boolean same = true; for (int y = 0; y < members.length; y++) { final MemberCell memberInfo = new MemberCell(); final Member member = members[y]; int index = memberList.indexOf(member); if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); if (depth_i > 0) { expanded = true; } } memberInfo.setExpanded(expanded); same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member); if (member != null) { if (x - 1 == offset) memberInfo.setLastRow(true); matrix.setOffset(oldoffset); memberInfo.setRawValue(member.getCaption()); memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value memberInfo.setParentDimension(member.getDimension().getName()); memberInfo.setUniquename(member.getUniqueName()); memberInfo.setHierarchy(member.getHierarchy().getUniqueName()); memberInfo.setLevel(member.getLevel().getUniqueName()); // try { // memberInfo.setChildMemberCount(member.getChildMemberCount()); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // NamedList<Property> values = member.getLevel().getProperties(); // for(int j=0; j<values.size();j++){ // String val; // try { // val = member.getPropertyFormattedValue(values.get(j)); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // memberInfo.setProperty(values.get(j).getCaption(), val); // } // if (y > 0) { // for (int previ = y-1; previ >= 0;previ--) { // if(prevMembers[previ] != null) { // memberInfo.setRightOf(prevMemberInfo[previ]); // memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName()); // previ = -1; // } // } // } // if (member.getParentMember() != null) // memberInfo.setParentMember(member.getParentMember().getUniqueName()); } else { memberInfo.setRawValue(null); memberInfo.setFormattedValue(null); memberInfo.setParentDimension(null); } if (isColumns) { memberInfo.setRight(false); memberInfo.setSameAsPrev(same); if (member != null) memberInfo.setParentDimension(member.getDimension().getName()); matrix.set(x, y, memberInfo); } else { memberInfo.setRight(false); memberInfo.setSameAsPrev(false); matrix.set(y, x, memberInfo); } int x_parent = isColumns ? x : y-1; int y_parent = isColumns ? y-1 : x; if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); while (depth_i > 0) { depth_i--; int parentDepth = (ordinalInfo.getDepths().get(depth_i)); Member parent = member.getParentMember(); while (parent != null && parent.getDepth() > parentDepth) { parent = parent.getParentMember(); } final MemberCell pInfo = new MemberCell(); if (parent != null) { pInfo.setRawValue(parent.getCaption()); pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value pInfo.setParentDimension(parent.getDimension().getName()); pInfo.setHierarchy(parent.getHierarchy().getUniqueName()); pInfo.setUniquename(parent.getUniqueName()); pInfo.setLevel(parent.getLevel().getUniqueName()); } else { pInfo.setRawValue(""); pInfo.setFormattedValue(""); // First try to get a formatted value pInfo.setParentDimension(member.getDimension().getName()); pInfo.setHierarchy(member.getHierarchy().getUniqueName()); pInfo.setLevel(member.getLevel().getUniqueName()); pInfo.setUniquename(""); } matrix.set(x_parent, y_parent, pInfo); if (isColumns) { y_parent--; } else { x_parent--; } } } prevMembers[y] = member; prevMemberInfo[y] = memberInfo; members[y] = null; } } }
private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo, final boolean isColumns, final int oldoffset) { int offset = oldoffset; if (axis == null) return; final Member[] prevMembers = new Member[axisInfo.getWidth()]; final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()]; final Member[] members = new Member[axisInfo.getWidth()]; for (int i = 0; i < axis.getPositions().size(); i++) { final int x = offset + i; final Position position = axis.getPositions().get(i); int yOffset = 0; final List<Member> memberList = position.getMembers(); boolean stop = false; for (int j = 0; j < memberList.size(); j++) { Member member = memberList.get(j); final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j); List<Integer> depths = ordinalInfo.depths; Collections.sort(depths); if (member.getDepth() < Collections.max(depths)) { stop = true; if (isColumns) { ignorex.add(i); } else { ignorey.add(i); } break; } if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0)) break; final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth()); members[y] = member; yOffset += ordinalInfo.getWidth(); } if (stop) { offset--; continue; } boolean expanded = false; boolean same = true; for (int y = 0; y < members.length; y++) { final MemberCell memberInfo = new MemberCell(); final Member member = members[y]; int index = memberList.indexOf(member); if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); if (depth_i > 0) { expanded = true; } } memberInfo.setExpanded(expanded); same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member); if (member != null) { if (x - 1 == offset) memberInfo.setLastRow(true); matrix.setOffset(oldoffset); memberInfo.setRawValue(member.getCaption()); memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value memberInfo.setParentDimension(member.getDimension().getName()); memberInfo.setUniquename(member.getUniqueName()); memberInfo.setHierarchy(member.getHierarchy().getUniqueName()); memberInfo.setLevel(member.getLevel().getUniqueName()); // try { // memberInfo.setChildMemberCount(member.getChildMemberCount()); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // NamedList<Property> values = member.getLevel().getProperties(); // for(int j=0; j<values.size();j++){ // String val; // try { // val = member.getPropertyFormattedValue(values.get(j)); // } catch (OlapException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // memberInfo.setProperty(values.get(j).getCaption(), val); // } // if (y > 0) { // for (int previ = y-1; previ >= 0;previ--) { // if(prevMembers[previ] != null) { // memberInfo.setRightOf(prevMemberInfo[previ]); // memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName()); // previ = -1; // } // } // } // if (member.getParentMember() != null) // memberInfo.setParentMember(member.getParentMember().getUniqueName()); } else { memberInfo.setRawValue(null); memberInfo.setFormattedValue(null); memberInfo.setParentDimension(null); } if (isColumns) { memberInfo.setRight(false); memberInfo.setSameAsPrev(same); if (member != null) memberInfo.setParentDimension(member.getDimension().getName()); matrix.set(x, y, memberInfo); } else { memberInfo.setRight(false); memberInfo.setSameAsPrev(false); matrix.set(y, x, memberInfo); } int x_parent = isColumns ? x : y-1; int y_parent = isColumns ? y-1 : x; if (index >= 0) { final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index); int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth()); while (depth_i > 0) { depth_i--; int parentDepth = (ordinalInfo.getDepths().get(depth_i)); Member parent = member.getParentMember(); while (parent != null && parent.getDepth() > parentDepth) { parent = parent.getParentMember(); } final MemberCell pInfo = new MemberCell(); if (parent != null) { pInfo.setRawValue(parent.getCaption()); pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value pInfo.setParentDimension(parent.getDimension().getName()); pInfo.setHierarchy(parent.getHierarchy().getUniqueName()); pInfo.setUniquename(parent.getUniqueName()); pInfo.setLevel(parent.getLevel().getUniqueName()); } else { pInfo.setRawValue(""); pInfo.setFormattedValue(""); // First try to get a formatted value pInfo.setParentDimension(member.getDimension().getName()); pInfo.setHierarchy(member.getHierarchy().getUniqueName()); pInfo.setLevel(member.getLevel().getUniqueName()); pInfo.setUniquename(""); } matrix.set(x_parent, y_parent, pInfo); if (isColumns) { y_parent--; } else { x_parent--; } } } prevMembers[y] = member; prevMemberInfo[y] = memberInfo; members[y] = null; } } }
diff --git a/SearchAndFind/src/main/java/de/haas/searchandfind/backend/Indexer.java b/SearchAndFind/src/main/java/de/haas/searchandfind/backend/Indexer.java index 170c53e..5131244 100644 --- a/SearchAndFind/src/main/java/de/haas/searchandfind/backend/Indexer.java +++ b/SearchAndFind/src/main/java/de/haas/searchandfind/backend/Indexer.java @@ -1,87 +1,87 @@ package de.haas.searchandfind.backend; import de.haas.searchandfind.backend.filesource.FileWrapper; import de.haas.searchandfind.backend.filesource.FileWatcher; import de.haas.searchandfind.backend.filesource.FileLister; import de.haas.searchandfind.backend.documentgenerator.DocumentFactory; import java.io.File; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Version; /** * * @author Michael Haas <[email protected]> */ public class Indexer extends Thread { // TODO: sensible value private static final int MAX_FIELD_LENGTH = 500; private BlockingQueue<FileWrapper> queue = new LinkedBlockingQueue<FileWrapper>(); // TODO: is an IndexWriter threadsafe? Or do we need a singleton here? // "An IndexWriter creates and maintains an index. " private Directory directory; private File targetDir; public Indexer(File targetDirectory, Directory indexDirectory) { this.targetDir = targetDirectory; this.directory = indexDirectory; } @Override public void run() { try { this.kickOffIndexing(); } catch (IOException ex) { Logger.getLogger(Indexer.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(Indexer.class.getName()).log(Level.SEVERE, null, ex); } } private void kickOffIndexing() throws IOException, InterruptedException { Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); IndexWriter.MaxFieldLength mfl = new IndexWriter.MaxFieldLength(MAX_FIELD_LENGTH); IndexWriter writer = new IndexWriter(this.directory, analyzer, mfl); // TODO: this is somewhat race-y. Ideally, we'd start the FileWatcher once // all files are read by the FileLister. On the other hand, we might miss // newly created files in this case. FileLister lister = new FileLister(this.queue, this.targetDir); lister.start(); FileWatcher watcher = new FileWatcher(this.queue, this.targetDir); watcher.start(); // loop endlessly. // possibly add support for poison element in queue later on // OTOH, it's quite possible we want to keep indexing with the live // indexer forever and ever // TODO: filter out known documents while (true) { //for (int i = 0; i < 1; i++) { //System.out.println(i); File file = this.queue.take().getFile(); Logger.getLogger(Indexer.class.getName()).log(Level.INFO, "Creating Document for file " + file.getCanonicalPath()); Document document = DocumentFactory.getDocument(file); if (document == null) { - Logger.getLogger(Indexer.class.getName()).log(Level.SEVERE, "Document as returned by Factory is null. Skipping"); + Logger.getLogger(Indexer.class.getName()).log(Level.INFO, "Document as returned by Factory is null. Skipping"); continue; } writer.addDocument(document); writer.commit(); } //writer.close(); } }
true
true
private void kickOffIndexing() throws IOException, InterruptedException { Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); IndexWriter.MaxFieldLength mfl = new IndexWriter.MaxFieldLength(MAX_FIELD_LENGTH); IndexWriter writer = new IndexWriter(this.directory, analyzer, mfl); // TODO: this is somewhat race-y. Ideally, we'd start the FileWatcher once // all files are read by the FileLister. On the other hand, we might miss // newly created files in this case. FileLister lister = new FileLister(this.queue, this.targetDir); lister.start(); FileWatcher watcher = new FileWatcher(this.queue, this.targetDir); watcher.start(); // loop endlessly. // possibly add support for poison element in queue later on // OTOH, it's quite possible we want to keep indexing with the live // indexer forever and ever // TODO: filter out known documents while (true) { //for (int i = 0; i < 1; i++) { //System.out.println(i); File file = this.queue.take().getFile(); Logger.getLogger(Indexer.class.getName()).log(Level.INFO, "Creating Document for file " + file.getCanonicalPath()); Document document = DocumentFactory.getDocument(file); if (document == null) { Logger.getLogger(Indexer.class.getName()).log(Level.SEVERE, "Document as returned by Factory is null. Skipping"); continue; } writer.addDocument(document); writer.commit(); } //writer.close(); }
private void kickOffIndexing() throws IOException, InterruptedException { Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); IndexWriter.MaxFieldLength mfl = new IndexWriter.MaxFieldLength(MAX_FIELD_LENGTH); IndexWriter writer = new IndexWriter(this.directory, analyzer, mfl); // TODO: this is somewhat race-y. Ideally, we'd start the FileWatcher once // all files are read by the FileLister. On the other hand, we might miss // newly created files in this case. FileLister lister = new FileLister(this.queue, this.targetDir); lister.start(); FileWatcher watcher = new FileWatcher(this.queue, this.targetDir); watcher.start(); // loop endlessly. // possibly add support for poison element in queue later on // OTOH, it's quite possible we want to keep indexing with the live // indexer forever and ever // TODO: filter out known documents while (true) { //for (int i = 0; i < 1; i++) { //System.out.println(i); File file = this.queue.take().getFile(); Logger.getLogger(Indexer.class.getName()).log(Level.INFO, "Creating Document for file " + file.getCanonicalPath()); Document document = DocumentFactory.getDocument(file); if (document == null) { Logger.getLogger(Indexer.class.getName()).log(Level.INFO, "Document as returned by Factory is null. Skipping"); continue; } writer.addDocument(document); writer.commit(); } //writer.close(); }
diff --git a/net.sf.jmoney/src/net/sf/jmoney/model2/ChangeManager.java b/net.sf.jmoney/src/net/sf/jmoney/model2/ChangeManager.java index 35c3f1fb..c6266841 100644 --- a/net.sf.jmoney/src/net/sf/jmoney/model2/ChangeManager.java +++ b/net.sf.jmoney/src/net/sf/jmoney/model2/ChangeManager.java @@ -1,443 +1,444 @@ /* * * JMoney - A Personal Finance Manager * Copyright (c) 2004 Nigel Westbury <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ package net.sf.jmoney.model2; import java.util.Collection; import java.util.Vector; /** * Keeps track of changes made to the model. This is done to enable the * undo/redo feature. * * As changes are undone and redone, the id of each object may change. * For example, in the serializeddatastore plug-in, the id of each object * is a reference to the object itself, i.e. the java identity. Unless * we keep a reference to these objects, which we don't, the identity of * objects will not be the same when the object is re-created. (Even if * we kept a reference to an object, it is not possible to insert that * object back into the object store for various technical reasons). * If the datastore is a database, for example in the jdbcdatastore plug-in, * the id is automatically generated as a value of a unique column. * The database may decide to re-use the id of a delete row. * Therefore, this class never stores ids of objects that have been * deleted. When an object is deleted, all old values that reference * the object are replaced with references to the delete entry. * This allows the data to be re-created correctly by the undo method. * * @author Nigel Westbury */ public class ChangeManager { /** * When we delete an object, we know that nothing in the * datastore references it. However, there may be old * values that referenced it. It is important that these * old values are updated to reference this deleted object. * Otherwise, if the object is re-created with a different * id then those old values cannot be restored correctly. */ private class KeyProxy { IObjectKey key; KeyProxy(IObjectKey key) { this.key = key; } } /* * If there are no references to the KeyProxy then this means there are no changes that * need the key proxy to undo the change. The entry can be removed from the map. * Thus we use a map with weak value references. */ private WeakValuedMap<IObjectKey, KeyProxy> keyProxyMap = new WeakValuedMap<IObjectKey, KeyProxy>(); private UndoableChange currentUndoableChange = null; public class UndoableChange { /** * Vector of ChangeEntry objects. Changes are added to * this vector in order. If changes are undone, they must * be undone in reverse order, starting at the end of this * vector. */ private Vector<ChangeEntry> changes = new Vector<ChangeEntry>(); /** * Submit a series of updates, which have been stored, * to the datastore. These updates carry out the reverse * of the updates stored. */ public void undoChanges() { // Undo the changes in reverse order. for (int i = changes.size() - 1; i >= 0; i--) { ChangeEntry changeEntry = changes.get(i); changeEntry.undo(); } } /** * @param newChangeEntry */ void addChange(ChangeEntry newChangeEntry) { changes.add(newChangeEntry); } } /** * Base class for all objects that represent a component of * a change. Derived classes represent property changes, * insertion of new objects, and deletion of objects. * * These objects have only a constructor and the <code>undo</code> method. * Once the <code>undo</code> is called the object is dead. */ abstract class ChangeEntry { abstract void undo(); } /** * A ChangeEntry object for an update to a scalar property (excluding * scalar properties that are references to extendable objects). * * @param <V> */ class ChangeEntry_UpdateScalar<V> extends ChangeEntry { private KeyProxy objectKeyProxy; private ScalarPropertyAccessor<V> propertyAccessor; private V oldValue = null; ChangeEntry_UpdateScalar(KeyProxy objectKeyProxy, ScalarPropertyAccessor<V> propertyAccessor, V oldValue) { this.objectKeyProxy = objectKeyProxy; this.propertyAccessor = propertyAccessor; this.oldValue = oldValue; } void undo() { ExtendableObject object = objectKeyProxy.key.getObject(); // efficient??? object.setPropertyValue(propertyAccessor, oldValue); } } /** * A ChangeEntry object for an update to a scalar property that is a * reference to an extendable object. * * @param <E> */ // TODO: E should be bounded to classes that extend ExtendableObject. // However, this method does not currently make use of such bounding, // and to do that we would have to push back seperate methods for // reference properties and other scalar properties. class ChangeEntry_UpdateReference<E> extends ChangeEntry { private KeyProxy objectKeyProxy; private ScalarPropertyAccessor<E> propertyAccessor; private KeyProxy oldValueProxy = null; ChangeEntry_UpdateReference(KeyProxy objectKeyProxy, ScalarPropertyAccessor<E> propertyAccessor, KeyProxy oldValueProxy) { this.objectKeyProxy = objectKeyProxy; this.propertyAccessor = propertyAccessor; this.oldValueProxy = oldValueProxy; } void undo() { ExtendableObject object = objectKeyProxy.key.getObject(); // efficient??? // If IObjectKey had a type parameter, we would not need // this cast. object.setPropertyValue(propertyAccessor, propertyAccessor .getClassOfValueObject() .cast(oldValueProxy.key.getObject())); } } class ChangeEntry_Insert extends ChangeEntry { private KeyProxy parentKeyProxy; private ListPropertyAccessor<?> owningListProperty; private KeyProxy objectKeyProxy; ChangeEntry_Insert(KeyProxy parentKeyProxy, ListPropertyAccessor<?> owningListProperty, KeyProxy objectKeyProxy) { this.parentKeyProxy = parentKeyProxy; this.owningListProperty = owningListProperty; this.objectKeyProxy = objectKeyProxy; } void undo() { // Delete the object. ExtendableObject object = objectKeyProxy.key.getObject(); // efficient??? ExtendableObject parent = parentKeyProxy.key.getObject(); // Delete the object from the datastore. parent.getListPropertyValue(owningListProperty).remove(object); } } /** * @param <E> the type of the object being deleted */ class ChangeEntry_Delete<E extends ExtendableObject> extends ChangeEntry { private Object[] oldValues; private Collection<ExtensionPropertySet<?>> nonDefaultExtensions; private KeyProxy parentKeyProxy; private ListPropertyAccessor<E> owningListProperty; private KeyProxy objectKeyProxy; private ExtendablePropertySet<? extends E> actualPropertySet; ChangeEntry_Delete(KeyProxy parentKeyProxy, ListPropertyAccessor<E> owningListProperty, E oldObject) { this.parentKeyProxy = parentKeyProxy; this.owningListProperty = owningListProperty; this.objectKeyProxy = getKeyProxy(oldObject.getObjectKey()); this.actualPropertySet = owningListProperty.getElementPropertySet() .getActualPropertySet( (Class<? extends E>) oldObject.getClass()); /* * Save all the property values from the deleted object. We need * these to re-create the object if this change is undone. */ nonDefaultExtensions = oldObject.getExtensions(); int count = actualPropertySet.getScalarProperties3().size(); oldValues = new Object[count]; int index = 0; for (ScalarPropertyAccessor<?> propertyAccessor : actualPropertySet .getScalarProperties3()) { if (index != propertyAccessor.getIndexIntoScalarProperties()) { throw new RuntimeException("index mismatch"); } Object value = oldObject.getPropertyValue(propertyAccessor); if (value instanceof ExtendableObject) { /* * We can't store extendable objects or even the object keys * because those may not remain valid (the referenced object may * be deleted). We store instead a KeyProxy. If the referenced * object is later deleted, then un-deleted using an undo * operation, then this change is also undone, the key proxy * will give us the new object key for the referenced object. */ IObjectKey objectKey = ((ExtendableObject) value) .getObjectKey(); oldValues[index++] = getKeyProxy(objectKey); } else { oldValues[index++] = value; } } } void undo() { /* Create the object in the datastore. * However, we must first convert the key proxies back to keys before passing * on to the constructor. */ IValues oldValues2 = new IValues() { public <V> V getScalarValue(ScalarPropertyAccessor<V> propertyAccessor) { return propertyAccessor.getClassOfValueObject().cast(oldValues[propertyAccessor.getIndexIntoScalarProperties()]); } public IObjectKey getReferencedObjectKey( ScalarPropertyAccessor<? extends ExtendableObject> propertyAccessor) { - return ((KeyProxy)oldValues[propertyAccessor.getIndexIntoScalarProperties()]).key; + KeyProxy keyProxy = (KeyProxy)oldValues[propertyAccessor.getIndexIntoScalarProperties()]; + return keyProxy == null ? null : keyProxy.key; } public <E2 extends ExtendableObject> IListManager<E2> getListManager( IObjectKey listOwnerKey, ListPropertyAccessor<E2> listAccessor) { return listOwnerKey.constructListManager(listAccessor); } public Collection<ExtensionPropertySet<?>> getNonDefaultExtensions() { return nonDefaultExtensions; } }; ExtendableObject parent = parentKeyProxy.key.getObject(); ExtendableObject object = parent.getListPropertyValue( owningListProperty).createNewElement(actualPropertySet, oldValues2, false); /* * Set the new object key back into the proxy. This ensures that * earlier changes to this object will be undone in this object. We * must also add to our map so that if further changes are made that * reference this object key, they will be using the same proxy. */ if (objectKeyProxy.key != null) { throw new RuntimeException("internal error - key proxy error"); } objectKeyProxy.key = object.getObjectKey(); keyProxyMap.put(objectKeyProxy.key, objectKeyProxy); } } private KeyProxy getKeyProxy(IObjectKey objectKey) { if (objectKey != null) { KeyProxy keyProxy = keyProxyMap.get(objectKey); if (keyProxy == null) { keyProxy = new KeyProxy(objectKey); keyProxyMap.put(objectKey, keyProxy); } return keyProxy; } else { return null; } } private void addUndoableChangeEntry(ChangeEntry changeEntry) { if (currentUndoableChange != null) { currentUndoableChange.addChange(changeEntry); } /* * If changes are made while currentUndoableChange is set to null then * the changes are not undoable. This is supported but is not common. It * is typically used for very large transactions such as imports of * entire databases by the copier plug-in. */ // TODO: We should really clear out the change history as // prior changes are not likely to be undoable after this // change has been applied. } /** * The property may be any property in the passed object. * The property may be defined in the actual class or * any super classes which the class extends. The property * may also be a property in any extension class which extends * the class of this object or which extends any super class * of the class of this object. */ public <V> void processPropertyUpdate(ExtendableObject object, ScalarPropertyAccessor<V> propertyAccessor, V oldValue, V newValue) { // Replace any keys with proxy keys if (propertyAccessor.getClassOfValueObject().isAssignableFrom(ExtendableObject.class)) { ChangeEntry newChangeEntry = new ChangeEntry_UpdateReference<V>( getKeyProxy(object.getObjectKey()), propertyAccessor, getKeyProxy((IObjectKey) oldValue)); addUndoableChangeEntry(newChangeEntry); } else { ChangeEntry newChangeEntry = new ChangeEntry_UpdateScalar<V>( getKeyProxy(object.getObjectKey()), propertyAccessor, oldValue); addUndoableChangeEntry(newChangeEntry); } } public void processObjectCreation(ExtendableObject parent, ListPropertyAccessor<?> owningListProperty, ExtendableObject newObject) { ChangeEntry newChangeEntry = new ChangeEntry_Insert(getKeyProxy(parent .getObjectKey()), owningListProperty, getKeyProxy(newObject .getObjectKey())); addUndoableChangeEntry(newChangeEntry); } /** * Processes the deletion of an object. This involves adding the property * values to the change list so that the deletion can be undone. * <P> * Also we must call this method recursively on any objects contained in any * list properties in the object. This is because this object 'owns' such * objects, and so those objects will also be deleted and must be restored * if this operation is undone. * * @param <E> * @param parent * @param owningListProperty * @param oldObject */ public <E extends ExtendableObject> void processObjectDeletion( ExtendableObject parent, ListPropertyAccessor<E> owningListProperty, E oldObject) { /* * We must also process objects owned by this object in a recursive * manner. Otherwise, undoing the deletion of an object will not restore * any objects owned by that object. */ for (ListPropertyAccessor<?> subList : PropertySet.getPropertySet(oldObject.getClass()).getListProperties3()) { processObjectListDeletion(oldObject, subList); } ChangeEntry_Delete<E> newChangeEntry = new ChangeEntry_Delete<E>( getKeyProxy(parent.getObjectKey()), owningListProperty, oldObject); /* * The actual key is no longer valid, so we remove the proxy from the * map that maps object keys to proxies. For safety we also set this to * null. * * Note that the proxy itself still exists. If this deletion is later * undone then the object is re-inserted and will be given a new object * key by the underlying datastore. That new object key will then be set in * the proxy and the proxy will be added back to the map with the new * object key. */ // Remove from the map. keyProxyMap.remove(newChangeEntry.objectKeyProxy.key); // This line may not be needed, as the key should never // be accessed if the proxy represents a key that currently // does not exist in the datastore. This line is here for // safety only. newChangeEntry.objectKeyProxy.key = null; addUndoableChangeEntry(newChangeEntry); } /** * Helper function to process the deletion of all objects in a list * property. * * @param <E> * @param parent the object containing the list * @param listProperty the property accessor for the list */ private <E extends ExtendableObject> void processObjectListDeletion(ExtendableObject parent, ListPropertyAccessor<E> listProperty) { for (E childObject : parent.getListPropertyValue(listProperty)) { processObjectDeletion(parent, listProperty, childObject); } } public void setUndoableChange() { currentUndoableChange = new UndoableChange(); } public UndoableChange takeUndoableChange() { UndoableChange result = currentUndoableChange; currentUndoableChange = null; return result; } }
true
true
void undo() { /* Create the object in the datastore. * However, we must first convert the key proxies back to keys before passing * on to the constructor. */ IValues oldValues2 = new IValues() { public <V> V getScalarValue(ScalarPropertyAccessor<V> propertyAccessor) { return propertyAccessor.getClassOfValueObject().cast(oldValues[propertyAccessor.getIndexIntoScalarProperties()]); } public IObjectKey getReferencedObjectKey( ScalarPropertyAccessor<? extends ExtendableObject> propertyAccessor) { return ((KeyProxy)oldValues[propertyAccessor.getIndexIntoScalarProperties()]).key; } public <E2 extends ExtendableObject> IListManager<E2> getListManager( IObjectKey listOwnerKey, ListPropertyAccessor<E2> listAccessor) { return listOwnerKey.constructListManager(listAccessor); } public Collection<ExtensionPropertySet<?>> getNonDefaultExtensions() { return nonDefaultExtensions; } }; ExtendableObject parent = parentKeyProxy.key.getObject(); ExtendableObject object = parent.getListPropertyValue( owningListProperty).createNewElement(actualPropertySet, oldValues2, false); /* * Set the new object key back into the proxy. This ensures that * earlier changes to this object will be undone in this object. We * must also add to our map so that if further changes are made that * reference this object key, they will be using the same proxy. */ if (objectKeyProxy.key != null) { throw new RuntimeException("internal error - key proxy error"); } objectKeyProxy.key = object.getObjectKey(); keyProxyMap.put(objectKeyProxy.key, objectKeyProxy); }
void undo() { /* Create the object in the datastore. * However, we must first convert the key proxies back to keys before passing * on to the constructor. */ IValues oldValues2 = new IValues() { public <V> V getScalarValue(ScalarPropertyAccessor<V> propertyAccessor) { return propertyAccessor.getClassOfValueObject().cast(oldValues[propertyAccessor.getIndexIntoScalarProperties()]); } public IObjectKey getReferencedObjectKey( ScalarPropertyAccessor<? extends ExtendableObject> propertyAccessor) { KeyProxy keyProxy = (KeyProxy)oldValues[propertyAccessor.getIndexIntoScalarProperties()]; return keyProxy == null ? null : keyProxy.key; } public <E2 extends ExtendableObject> IListManager<E2> getListManager( IObjectKey listOwnerKey, ListPropertyAccessor<E2> listAccessor) { return listOwnerKey.constructListManager(listAccessor); } public Collection<ExtensionPropertySet<?>> getNonDefaultExtensions() { return nonDefaultExtensions; } }; ExtendableObject parent = parentKeyProxy.key.getObject(); ExtendableObject object = parent.getListPropertyValue( owningListProperty).createNewElement(actualPropertySet, oldValues2, false); /* * Set the new object key back into the proxy. This ensures that * earlier changes to this object will be undone in this object. We * must also add to our map so that if further changes are made that * reference this object key, they will be using the same proxy. */ if (objectKeyProxy.key != null) { throw new RuntimeException("internal error - key proxy error"); } objectKeyProxy.key = object.getObjectKey(); keyProxyMap.put(objectKeyProxy.key, objectKeyProxy); }
diff --git a/src/Player.java b/src/Player.java index 5350179..7f23753 100644 --- a/src/Player.java +++ b/src/Player.java @@ -1,105 +1,105 @@ import java.util.ArrayList; public class Player { public ArrayList<Card> hand, bag, lockedCards, discard; public ArrayList<Integer> gemPile; public int money, blackTurns, redTurns, blueTurns, purpleTurns, brownTurns; public Player(){ this.gemPile = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) { gemPile.add(0); } this.hand = new ArrayList<Card>(); this.bag = new ArrayList<Card>(); this.discard = new ArrayList<Card>(); this.lockedCards = new ArrayList<Card>(); newTurn(); } public void setup() { Card initGem = new Card(); for (int i = 0; i < 5; i++) { this.bag.add(initGem); } ArrayList<CardColor> w = new ArrayList<CardColor>(); w.add(CardColor.GREY); ArrayList<Integer> e = new ArrayList<Integer>(); e.add(17); - Card wound = new Card(w, 5, CardType.CIRCLE, e, false, 0); + Card wound = new Card("Wound", w, 5, CardType.CIRCLE, e, false, 0); for (int i = 0; i < 3; i++) { this.bag.add(wound); } w = new ArrayList<CardColor>(); w.add(CardColor.PURPLE); e = new ArrayList<Integer>(); e.add(23); - Card crash = new Card(w, 1, CardType.CIRCLE, e, false, 1); + Card crash = new Card("CrashGem", w, 1, CardType.CIRCLE, e, false, 1); this.bag.add(crash); this.gemPile.set(0, this.gemPile.get(0) + 1); this.drawFromBag(5); } public void newTurn() { this.money = 0; this.blackTurns = 1; this.blueTurns = 0; this.purpleTurns = 0; this.brownTurns = 0; this.redTurns = 0; } public void endTurn() { int num = this.hand.size(); for (int i = 0; i < num; i++) { this.discard.add(this.hand.remove(0)); } //this.drawFromBag(5); } public void drawFromBag(int n) { for (int i = 0; i < n; i++) { if (this.bag.size() == 0) { this.bag = discard; this.discard = new ArrayList<Card>(); } if (lockedCards.size() > 0) { this.hand.add(this.lockedCards.remove(0)); } else { int nextCard = (int) (Math.random() * this.bag.size()); this.hand.add(this.bag.remove(nextCard)); } } } public void setHand(ArrayList<Card> cards) { this.hand = cards; } public void setBag(ArrayList<Card> cards) { this.bag = cards; } public void setDiscard(ArrayList<Card> cards) { this.discard = cards; } public ArrayList<Card> getHand() { return this.hand; } public ArrayList<Card> getBag() { return this.bag; } public ArrayList<Card> getDiscard() { return this.discard; } }
false
true
public void setup() { Card initGem = new Card(); for (int i = 0; i < 5; i++) { this.bag.add(initGem); } ArrayList<CardColor> w = new ArrayList<CardColor>(); w.add(CardColor.GREY); ArrayList<Integer> e = new ArrayList<Integer>(); e.add(17); Card wound = new Card(w, 5, CardType.CIRCLE, e, false, 0); for (int i = 0; i < 3; i++) { this.bag.add(wound); } w = new ArrayList<CardColor>(); w.add(CardColor.PURPLE); e = new ArrayList<Integer>(); e.add(23); Card crash = new Card(w, 1, CardType.CIRCLE, e, false, 1); this.bag.add(crash); this.gemPile.set(0, this.gemPile.get(0) + 1); this.drawFromBag(5); }
public void setup() { Card initGem = new Card(); for (int i = 0; i < 5; i++) { this.bag.add(initGem); } ArrayList<CardColor> w = new ArrayList<CardColor>(); w.add(CardColor.GREY); ArrayList<Integer> e = new ArrayList<Integer>(); e.add(17); Card wound = new Card("Wound", w, 5, CardType.CIRCLE, e, false, 0); for (int i = 0; i < 3; i++) { this.bag.add(wound); } w = new ArrayList<CardColor>(); w.add(CardColor.PURPLE); e = new ArrayList<Integer>(); e.add(23); Card crash = new Card("CrashGem", w, 1, CardType.CIRCLE, e, false, 1); this.bag.add(crash); this.gemPile.set(0, this.gemPile.get(0) + 1); this.drawFromBag(5); }
diff --git a/src/java/src/yarp/os/OutputPort.java b/src/java/src/yarp/os/OutputPort.java index 640f3d20..738a9271 100644 --- a/src/java/src/yarp/os/OutputPort.java +++ b/src/java/src/yarp/os/OutputPort.java @@ -1,85 +1,85 @@ package yarp.os; import java.lang.*; import java.io.*; public class OutputPort { private ContentCreator creator; private Content content; private BasicPort port; public void creator(ContentCreator creator) { this.creator = creator; } public void register(String name) { Address server = NameClient.getNameClient().register(name); Logger.get().info("Registered output port " + name + " as " + server.toString()); port = new BasicPort(server,name); port.start(); } public void connect(String name) { if (port==null) { Logger.get().error("Please call register() before connect()"); System.exit(1); } if (creator==null) { Logger.get().error("Please call creator() before connect()"); System.exit(1); } NameClient nc = NameClient.getNameClient(); String base = NameClient.getNamePart(name); String carrier = NameClient.getProtocolPart(name); Address add = nc.query(base); if (add==null) { Logger.get().error("Cannot find port " + base); return; } add = new Address(add.getName(),add.getPort(),carrier); Logger.get().println("connecting to address " + add.toString()); /* * Let's be polite and make sure the carrier is supported */ - if (NameClient.canConnect(port.getName(),base,carrier)) { + if (NameClient.canConnect(port.getPortName(),base,carrier)) { Connection c = null; try { c = new Connection(add,port.getPortName(),base); port.addConnection(c); } catch (IOException e) { Logger.get().error("Could not make connection"); } } } public Object content() { if (content==null) { content = creator.create(); } return content.object(); } public void write() { content(); port.send(content); content = null; } public void write(Content content) { port.send(content); } public void close() { port.close(); } }
true
true
public void connect(String name) { if (port==null) { Logger.get().error("Please call register() before connect()"); System.exit(1); } if (creator==null) { Logger.get().error("Please call creator() before connect()"); System.exit(1); } NameClient nc = NameClient.getNameClient(); String base = NameClient.getNamePart(name); String carrier = NameClient.getProtocolPart(name); Address add = nc.query(base); if (add==null) { Logger.get().error("Cannot find port " + base); return; } add = new Address(add.getName(),add.getPort(),carrier); Logger.get().println("connecting to address " + add.toString()); /* * Let's be polite and make sure the carrier is supported */ if (NameClient.canConnect(port.getName(),base,carrier)) { Connection c = null; try { c = new Connection(add,port.getPortName(),base); port.addConnection(c); } catch (IOException e) { Logger.get().error("Could not make connection"); } } }
public void connect(String name) { if (port==null) { Logger.get().error("Please call register() before connect()"); System.exit(1); } if (creator==null) { Logger.get().error("Please call creator() before connect()"); System.exit(1); } NameClient nc = NameClient.getNameClient(); String base = NameClient.getNamePart(name); String carrier = NameClient.getProtocolPart(name); Address add = nc.query(base); if (add==null) { Logger.get().error("Cannot find port " + base); return; } add = new Address(add.getName(),add.getPort(),carrier); Logger.get().println("connecting to address " + add.toString()); /* * Let's be polite and make sure the carrier is supported */ if (NameClient.canConnect(port.getPortName(),base,carrier)) { Connection c = null; try { c = new Connection(add,port.getPortName(),base); port.addConnection(c); } catch (IOException e) { Logger.get().error("Could not make connection"); } } }
diff --git a/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java b/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java index 3c17545b4..4dbbb4923 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java @@ -1,238 +1,235 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.network; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.SslContext; import org.apache.activemq.command.DiscoveryEvent; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportDisposedIOException; import org.apache.activemq.transport.TransportFactory; import org.apache.activemq.transport.discovery.DiscoveryAgent; import org.apache.activemq.transport.discovery.DiscoveryAgentFactory; import org.apache.activemq.transport.discovery.DiscoveryListener; import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.ServiceSupport; import org.apache.activemq.util.URISupport; import org.apache.activemq.util.URISupport.CompositeData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.ObjectName; /** * A network connector which uses a discovery agent to detect the remote brokers * available and setup a connection to each available remote broker * * @org.apache.xbean.XBean element="networkConnector" * */ public class DiscoveryNetworkConnector extends NetworkConnector implements DiscoveryListener { private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkConnector.class); private DiscoveryAgent discoveryAgent; private Map<String, String> parameters; public DiscoveryNetworkConnector() { } public DiscoveryNetworkConnector(URI discoveryURI) throws IOException { setUri(discoveryURI); } public void setUri(URI discoveryURI) throws IOException { setDiscoveryAgent(DiscoveryAgentFactory.createDiscoveryAgent(discoveryURI)); try { parameters = URISupport.parseParameters(discoveryURI); // allow discovery agent to grab it's parameters IntrospectionSupport.setProperties(getDiscoveryAgent(), parameters); } catch (URISyntaxException e) { LOG.warn("failed to parse query parameters from discoveryURI: " + discoveryURI, e); } } public void onServiceAdd(DiscoveryEvent event) { // Ignore events once we start stopping. if (serviceSupport.isStopped() || serviceSupport.isStopping()) { return; } String url = event.getServiceName(); if (url != null) { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } // Should we try to connect to that URI? if( bridges.containsKey(uri) ) { LOG.debug("Discovery agent generated a duplicate onServiceAdd event for: "+uri ); return; } if ( localURI.equals(uri) || (connectionFilter != null && !connectionFilter.connectTo(uri))) { LOG.debug("not connecting loopback: " + uri); return; } URI connectUri = uri; try { connectUri = URISupport.applyParameters(connectUri, parameters, DISCOVERED_OPTION_PREFIX); } catch (URISyntaxException e) { LOG.warn("could not apply query parameters: " + parameters + " to: " + connectUri, e); } LOG.info("Establishing network connection from " + localURI + " to " + connectUri); Transport remoteTransport; Transport localTransport; try { // Allows the transport to access the broker's ssl configuration. SslContext.setCurrentSslContext(getBrokerService().getSslContext()); try { remoteTransport = TransportFactory.connect(connectUri); } catch (Exception e) { LOG.warn("Could not connect to remote URI: " + connectUri + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } try { localTransport = createLocalTransport(); } catch (Exception e) { ServiceSupport.dispose(remoteTransport); LOG.warn("Could not connect to local URI: " + localURI + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } } finally { SslContext.setCurrentSslContext(null); } NetworkBridge bridge = createBridge(localTransport, remoteTransport, event); try { bridge.start(); bridges.put(uri, bridge); - } catch (TransportDisposedIOException e) { - LOG.warn("Network bridge between: " + localURI + " and: " + uri + " was correctly stopped before it was correctly started."); } catch (Exception e) { ServiceSupport.dispose(localTransport); ServiceSupport.dispose(remoteTransport); LOG.warn("Could not start network bridge between: " + localURI + " and: " + uri + " due to: " + e); LOG.debug("Start failure exception: " + e, e); try { discoveryAgent.serviceFailed(event); } catch (IOException e1) { LOG.debug("Discovery agent failure while handling failure event: " + e1.getMessage(), e1); } - return; } } } public void onServiceRemove(DiscoveryEvent event) { String url = event.getServiceName(); if (url != null) { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } NetworkBridge bridge = bridges.remove(uri); if (bridge == null) { return; } ServiceSupport.dispose(bridge); } } public DiscoveryAgent getDiscoveryAgent() { return discoveryAgent; } public void setDiscoveryAgent(DiscoveryAgent discoveryAgent) { this.discoveryAgent = discoveryAgent; if (discoveryAgent != null) { this.discoveryAgent.setDiscoveryListener(this); } } protected void handleStart() throws Exception { if (discoveryAgent == null) { throw new IllegalStateException("You must configure the 'discoveryAgent' property"); } this.discoveryAgent.start(); super.handleStart(); } protected void handleStop(ServiceStopper stopper) throws Exception { for (Iterator<NetworkBridge> i = bridges.values().iterator(); i.hasNext();) { NetworkBridge bridge = i.next(); try { bridge.stop(); } catch (Exception e) { stopper.onException(this, e); } } try { this.discoveryAgent.stop(); } catch (Exception e) { stopper.onException(this, e); } super.handleStop(stopper); } protected NetworkBridge createBridge(Transport localTransport, Transport remoteTransport, final DiscoveryEvent event) { class DiscoverNetworkBridgeListener extends MBeanNetworkListener { public DiscoverNetworkBridgeListener(BrokerService brokerService, ObjectName connectorName) { super(brokerService, connectorName); } public void bridgeFailed() { if (!serviceSupport.isStopped()) { try { discoveryAgent.serviceFailed(event); } catch (IOException e) { } } } } NetworkBridgeListener listener = new DiscoverNetworkBridgeListener(getBrokerService(), getObjectName()); DemandForwardingBridge result = NetworkBridgeFactory.createBridge(this, localTransport, remoteTransport, listener); result.setBrokerService(getBrokerService()); return configureBridge(result); } @Override public String toString() { return "DiscoveryNetworkConnector:" + getName() + ":" + getBrokerService(); } }
false
true
public void onServiceAdd(DiscoveryEvent event) { // Ignore events once we start stopping. if (serviceSupport.isStopped() || serviceSupport.isStopping()) { return; } String url = event.getServiceName(); if (url != null) { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } // Should we try to connect to that URI? if( bridges.containsKey(uri) ) { LOG.debug("Discovery agent generated a duplicate onServiceAdd event for: "+uri ); return; } if ( localURI.equals(uri) || (connectionFilter != null && !connectionFilter.connectTo(uri))) { LOG.debug("not connecting loopback: " + uri); return; } URI connectUri = uri; try { connectUri = URISupport.applyParameters(connectUri, parameters, DISCOVERED_OPTION_PREFIX); } catch (URISyntaxException e) { LOG.warn("could not apply query parameters: " + parameters + " to: " + connectUri, e); } LOG.info("Establishing network connection from " + localURI + " to " + connectUri); Transport remoteTransport; Transport localTransport; try { // Allows the transport to access the broker's ssl configuration. SslContext.setCurrentSslContext(getBrokerService().getSslContext()); try { remoteTransport = TransportFactory.connect(connectUri); } catch (Exception e) { LOG.warn("Could not connect to remote URI: " + connectUri + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } try { localTransport = createLocalTransport(); } catch (Exception e) { ServiceSupport.dispose(remoteTransport); LOG.warn("Could not connect to local URI: " + localURI + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } } finally { SslContext.setCurrentSslContext(null); } NetworkBridge bridge = createBridge(localTransport, remoteTransport, event); try { bridge.start(); bridges.put(uri, bridge); } catch (TransportDisposedIOException e) { LOG.warn("Network bridge between: " + localURI + " and: " + uri + " was correctly stopped before it was correctly started."); } catch (Exception e) { ServiceSupport.dispose(localTransport); ServiceSupport.dispose(remoteTransport); LOG.warn("Could not start network bridge between: " + localURI + " and: " + uri + " due to: " + e); LOG.debug("Start failure exception: " + e, e); try { discoveryAgent.serviceFailed(event); } catch (IOException e1) { LOG.debug("Discovery agent failure while handling failure event: " + e1.getMessage(), e1); } return; } } }
public void onServiceAdd(DiscoveryEvent event) { // Ignore events once we start stopping. if (serviceSupport.isStopped() || serviceSupport.isStopping()) { return; } String url = event.getServiceName(); if (url != null) { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } // Should we try to connect to that URI? if( bridges.containsKey(uri) ) { LOG.debug("Discovery agent generated a duplicate onServiceAdd event for: "+uri ); return; } if ( localURI.equals(uri) || (connectionFilter != null && !connectionFilter.connectTo(uri))) { LOG.debug("not connecting loopback: " + uri); return; } URI connectUri = uri; try { connectUri = URISupport.applyParameters(connectUri, parameters, DISCOVERED_OPTION_PREFIX); } catch (URISyntaxException e) { LOG.warn("could not apply query parameters: " + parameters + " to: " + connectUri, e); } LOG.info("Establishing network connection from " + localURI + " to " + connectUri); Transport remoteTransport; Transport localTransport; try { // Allows the transport to access the broker's ssl configuration. SslContext.setCurrentSslContext(getBrokerService().getSslContext()); try { remoteTransport = TransportFactory.connect(connectUri); } catch (Exception e) { LOG.warn("Could not connect to remote URI: " + connectUri + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } try { localTransport = createLocalTransport(); } catch (Exception e) { ServiceSupport.dispose(remoteTransport); LOG.warn("Could not connect to local URI: " + localURI + ": " + e.getMessage()); LOG.debug("Connection failure exception: " + e, e); return; } } finally { SslContext.setCurrentSslContext(null); } NetworkBridge bridge = createBridge(localTransport, remoteTransport, event); try { bridge.start(); bridges.put(uri, bridge); } catch (Exception e) { ServiceSupport.dispose(localTransport); ServiceSupport.dispose(remoteTransport); LOG.warn("Could not start network bridge between: " + localURI + " and: " + uri + " due to: " + e); LOG.debug("Start failure exception: " + e, e); try { discoveryAgent.serviceFailed(event); } catch (IOException e1) { LOG.debug("Discovery agent failure while handling failure event: " + e1.getMessage(), e1); } } } }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/ConnectionStep2.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/ConnectionStep2.java index 1e58d3af..1a5a518f 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/ConnectionStep2.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/ConnectionStep2.java @@ -1,95 +1,95 @@ package org.jboss.as.console.client.shared.subsys.jca.wizard; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.as.console.client.shared.BeanFactory; import org.jboss.as.console.client.shared.properties.PropertyEditor; import org.jboss.as.console.client.shared.properties.PropertyManagement; import org.jboss.as.console.client.shared.properties.PropertyRecord; import org.jboss.ballroom.client.widgets.window.DialogueOptions; import org.jboss.ballroom.client.widgets.window.WindowContentBuilder; import java.util.ArrayList; import java.util.List; /** * @author Heiko Braun * @date 7/20/11 */ public class ConnectionStep2 implements PropertyManagement { private NewConnectionWizard parent; private PropertyEditor propEditor; private List<PropertyRecord> properties; private BeanFactory factory = GWT.create(BeanFactory.class); public ConnectionStep2(NewConnectionWizard parent) { this.parent = parent; this.properties = new ArrayList<PropertyRecord>(); } @Override public void onCreateProperty(String reference, PropertyRecord prop) { } @Override public void onDeleteProperty(String reference, PropertyRecord prop) { properties.remove(prop); propEditor.setProperties("", properties); } @Override public void onChangeProperty(String reference, PropertyRecord prop) { // do nothing } @Override public void launchNewPropertyDialoge(String reference) { PropertyRecord proto = factory.property().as(); proto.setKey("name"); proto.setValue("value"); properties.add(proto); propEditor.setProperties("", properties); } @Override public void closePropertyDialoge() { } Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.setStyleName("window-content"); layout.add(new HTML("<h3>Connection Definiton Step2/2</h3>")); propEditor = new PropertyEditor(this, true); Widget widget = propEditor.asWidget(); layout.add(widget); ClickHandler submitHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { - parent.onCompleteStep2(properties); + // parent.onCompleteStep2(properties); } }; ClickHandler cancelHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { parent.getPresenter().closeDialoge(); } }; DialogueOptions options = new DialogueOptions( submitHandler, cancelHandler); return new WindowContentBuilder(layout,options).build(); } }
true
true
Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.setStyleName("window-content"); layout.add(new HTML("<h3>Connection Definiton Step2/2</h3>")); propEditor = new PropertyEditor(this, true); Widget widget = propEditor.asWidget(); layout.add(widget); ClickHandler submitHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { parent.onCompleteStep2(properties); } }; ClickHandler cancelHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { parent.getPresenter().closeDialoge(); } }; DialogueOptions options = new DialogueOptions( submitHandler, cancelHandler); return new WindowContentBuilder(layout,options).build(); }
Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.setStyleName("window-content"); layout.add(new HTML("<h3>Connection Definiton Step2/2</h3>")); propEditor = new PropertyEditor(this, true); Widget widget = propEditor.asWidget(); layout.add(widget); ClickHandler submitHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { // parent.onCompleteStep2(properties); } }; ClickHandler cancelHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { parent.getPresenter().closeDialoge(); } }; DialogueOptions options = new DialogueOptions( submitHandler, cancelHandler); return new WindowContentBuilder(layout,options).build(); }
diff --git a/tizzit-core/src/main/java/de/juwimm/cms/search/beans/SearchengineService.java b/tizzit-core/src/main/java/de/juwimm/cms/search/beans/SearchengineService.java index 62a1e93a..6794ebf3 100644 --- a/tizzit-core/src/main/java/de/juwimm/cms/search/beans/SearchengineService.java +++ b/tizzit-core/src/main/java/de/juwimm/cms/search/beans/SearchengineService.java @@ -1,717 +1,721 @@ package de.juwimm.cms.search.beans; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.compass.core.Compass; import org.compass.core.CompassHit; import org.compass.core.CompassHits; import org.compass.core.CompassQuery; import org.compass.core.CompassSession; import org.compass.core.CompassTransaction; import org.compass.core.Property; import org.compass.core.Resource; import org.compass.core.CompassQueryBuilder.CompassBooleanQueryBuilder; import org.compass.core.lucene.util.LuceneHelper; import org.compass.core.support.search.CompassSearchCommand; import org.compass.core.support.search.CompassSearchHelper; import org.compass.core.support.search.CompassSearchResults; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.tizzit.util.XercesHelper; import de.juwimm.cms.common.Constants; import de.juwimm.cms.model.ContentHbm; import de.juwimm.cms.model.ContentHbmDao; import de.juwimm.cms.model.ContentVersionHbm; import de.juwimm.cms.model.DocumentHbm; import de.juwimm.cms.model.DocumentHbmDao; import de.juwimm.cms.model.SiteHbm; import de.juwimm.cms.model.SiteHbmDao; import de.juwimm.cms.model.UnitHbm; import de.juwimm.cms.model.UnitHbmDao; import de.juwimm.cms.model.ViewComponentHbm; import de.juwimm.cms.model.ViewComponentHbmDao; import de.juwimm.cms.model.ViewDocumentHbm; import de.juwimm.cms.model.ViewDocumentHbmDao; import de.juwimm.cms.safeguard.remote.SafeguardServiceSpring; import de.juwimm.cms.search.res.DocumentResourceLocatorFactory; import de.juwimm.cms.search.res.HtmlResourceLocator; import de.juwimm.cms.search.vo.LinkDataValue; import de.juwimm.cms.search.vo.SearchResultValue; import de.juwimm.cms.search.vo.XmlSearchValue; import de.juwimm.cms.search.xmldb.XmlDb; /** * * @author <a href="mailto:[email protected]">Sascha-Matthias Kulawik</a> * company Juwi|MacMillan Group GmbH, Walsrode, Germany * @version $Id$ * @since cqcms-core 03.07.2009 */ @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) public class SearchengineService { private static Logger log = Logger.getLogger(SearchengineService.class); private static final String LUCENE_ESCAPE_CHARS = "[\\\\!\\(\\)\\:\\^\\]\\{\\}\\~]"; private static final Pattern LUCENE_PATTERN = Pattern.compile(LUCENE_ESCAPE_CHARS); private static final String REPLACEMENT_STRING = "\\\\$0"; @Autowired private Compass compass; @Autowired private XmlDb xmlDb; @Autowired private HtmlResourceLocator htmlResourceLocator; @Autowired private DocumentResourceLocatorFactory documentResourceLocatorFactory; @Autowired private SearchengineDeleteService searchengineDeleteService; @Autowired private SafeguardServiceSpring safeguardServiceSpring; private ViewComponentHbmDao viewComponentHbmDao; private SiteHbmDao siteHbmDao; private DocumentHbmDao documentHbmDao; private ContentHbmDao contentHbmDao; private ViewDocumentHbmDao viewDocumentHbmDao; private UnitHbmDao unitHbmDao; private final HttpClient client = new HttpClient(); public SafeguardServiceSpring getSafeguardServiceSpring() { return safeguardServiceSpring; } public void setSafeguardServiceSpring(SafeguardServiceSpring safeguardServiceSpring) { this.safeguardServiceSpring = safeguardServiceSpring; } public void setViewComponentHbmDao(ViewComponentHbmDao viewComponentHbmDao) { this.viewComponentHbmDao = viewComponentHbmDao; } public void setSiteHbmDao(SiteHbmDao siteHbmDao) { this.siteHbmDao = siteHbmDao; } public void setDocumentHbmDao(DocumentHbmDao documentHbmDao) { this.documentHbmDao = documentHbmDao; } public void setContentHbmDao(ContentHbmDao contentHbmDao) { this.contentHbmDao = contentHbmDao; } public void setViewDocumentHbmDao(ViewDocumentHbmDao viewDocumentHbmDao) { this.viewDocumentHbmDao = viewDocumentHbmDao; } public void setUnitHbmDao(UnitHbmDao unitHbmDao) { this.unitHbmDao = unitHbmDao; } public ViewComponentHbmDao getViewComponentHbmDao() { return viewComponentHbmDao; } public SiteHbmDao getSiteHbmDao() { return siteHbmDao; } public DocumentHbmDao getDocumentHbmDao() { return documentHbmDao; } public ContentHbmDao getContentHbmDao() { return contentHbmDao; } public ViewDocumentHbmDao getViewDocumentHbmDao() { return viewDocumentHbmDao; } public UnitHbmDao getUnitHbmDao() { return unitHbmDao; } /** * @see de.juwimm.cms.search.remote.SearchengineServiceSpring#searchXML(java.lang.Integer, java.lang.String) */ @Transactional(readOnly = true) public XmlSearchValue[] searchXML(Integer siteId, String xpathQuery) throws Exception { XmlSearchValue[] retString = null; retString = xmlDb.searchXml(siteId, xpathQuery); return retString; } /** * @see de.juwimm.cms.search.remote.SearchengineServiceSpring#startIndexer() */ public void startIndexer() throws Exception { try { Date start = new Date(); Collection sites = getSiteHbmDao().findAll(); Iterator itSites = sites.iterator(); while (itSites.hasNext()) { SiteHbm site = (SiteHbm) itSites.next(); if (log.isDebugEnabled()) log.debug("Starting with Site " + site.getName() + " (" + site.getSiteId() + ")"); reindexSite(site.getSiteId()); } Date end = new Date(); if (log.isInfoEnabled()) log.info(end.getTime() - start.getTime() + " total milliseconds"); } catch (Exception e) { log.error("Caught a " + e.getClass() + "\n with message: " + e.getMessage()); } } /** * @see de.juwimm.cms.search.remote.SearchengineServiceSpring#reindexSite(java.lang.Integer) */ @SuppressWarnings("unchecked") public void reindexSite(Integer siteId) throws Exception { if (log.isDebugEnabled()) log.debug("Starting reindexing site " + siteId); SiteHbm site = getSiteHbmDao().load(siteId); //if site with external site search then schedule it to the ExternalSitesCronService for indexing if (site.getExternalSiteSearch() != null && site.getExternalSiteSearch()) { site.setUpdateSiteIndex(true); return; } CompassSession session = compass.openSession(); CompassQuery query = session.queryBuilder().term("siteId", siteId); if (log.isDebugEnabled()) log.debug("delete sites with siteId: " + siteId + " with query: " + query.toString()); session.delete(query); session.close(); Date start = new Date(); try { Collection vdocs = getViewDocumentHbmDao().findAll(siteId); Iterator itVdocs = vdocs.iterator(); while (itVdocs.hasNext()) { ViewDocumentHbm vdl = (ViewDocumentHbm) itVdocs.next(); if (log.isDebugEnabled()) log.debug("- Starting ViewDocument: " + vdl.getLanguage() + " " + vdl.getViewType()); ViewComponentHbm rootvc = vdl.getViewComponent(); setUpdateSearchIndex4AllVCs(rootvc); } } catch (Exception e) { log.error("Caught a " + e.getClass() + "\n with message: " + e.getMessage()); } try { Collection<UnitHbm> units = getUnitHbmDao().findBySite(siteId); for (UnitHbm unit : units) { Collection<DocumentHbm> docs = getDocumentHbmDao().findAllPerUnit(unit.getUnitId()); for (DocumentHbm doc : docs) { // -- Indexing through No-Messaging doc.setUpdateSearchIndex(true); } } } catch (Exception e) { log.error("Caught a " + e.getClass() + "\n with message: " + e.getMessage()); } Date end = new Date(); if (log.isInfoEnabled()) log.info(end.getTime() - start.getTime() + " total milliseconds for site " + siteId); if (log.isDebugEnabled()) log.debug("finished index for site " + siteId); } private void setUpdateSearchIndex4AllVCs(ViewComponentHbm viewComponent) { if (!"DUMMY".equals(viewComponent.getReference())) { if (viewComponent.getViewType() == Constants.VIEW_TYPE_CONTENT || viewComponent.getViewType() == Constants.VIEW_TYPE_UNIT) { ContentHbm content = null; try { content = getContentHbmDao().load(new Integer(viewComponent.getReference())); // -- Indexing through No-Messaging content.setUpdateSearchIndex(true); } catch (Exception exe) { log.warn("Could not resolve Content with Id: " + viewComponent.getReference(), exe); } } if (!viewComponent.isLeaf()) { Collection children = viewComponent.getChildren(); Iterator itChildren = children.iterator(); while (itChildren.hasNext()) { ViewComponentHbm child = (ViewComponentHbm) itChildren.next(); setUpdateSearchIndex4AllVCs(child); } } } } private LinkDataValue[] getLinkData(Integer siteId, DocumentHbm doc) { Collection<LinkDataValue> linkDataList = new ArrayList<LinkDataValue>(); try { XmlSearchValue[] xmlData = this.searchXML(siteId, "//document[@src=\"" + doc.getDocumentId().toString() + "\"]"); if (xmlData != null && xmlData.length > 0) { for (int i = (xmlData.length - 1); i >= 0; i--) { LinkDataValue ldv = new LinkDataValue(); ldv.setUnitId(xmlData[i].getUnitId()); ldv.setViewComponentId(xmlData[i].getViewComponentId()); try { UnitHbm unit = getUnitHbmDao().load(ldv.getUnitId()); ldv.setUnitName(unit.getName()); } catch (Exception e) { log.error("Error loading Unit " + ldv.getUnitId() + ": Perhaps SearchIndex is corrupt? " + e.getMessage(), e); } try { ViewComponentHbm viewComponent = getViewComponentHbmDao().load(ldv.getViewComponentId()); ldv.setViewComponentPath(viewComponent.getPath()); ViewDocumentHbm viewDocument = viewComponent.getViewDocument(); ldv.setLanguage(viewDocument.getLanguage()); ldv.setViewType(viewDocument.getViewType()); } catch (Exception e) { log.error("Error loading ViewComponent " + ldv.getViewComponentId() + ": Perhaps SearchIndex is corrupt? " + e.getMessage(), e); } linkDataList.add(ldv); } } } catch (Exception e) { log.error("Error loading link-data for document " + doc.getDocumentId() + ": " + e.getMessage(), e); } return linkDataList.toArray(new LinkDataValue[0]); } @Transactional(readOnly = true) public XmlSearchValue[] searchXmlByUnit(Integer unitId, Integer viewDocumentId, String xpathQuery, boolean parentSearch) throws Exception { XmlSearchValue[] retString = null; if (parentSearch) { try { ViewComponentHbm vc = getViewComponentHbmDao().find4Unit(unitId, viewDocumentId); if (vc != null && !vc.isRoot()) { unitId = vc.getParent().getUnit4ViewComponent(); } } catch (Exception e) { log.error("Error finding VC by unit " + unitId + " and viewDocument " + viewDocumentId + " in searchXmlByUnit!", e); } } retString = xmlDb.searchXmlByUnit(unitId, viewDocumentId, xpathQuery); return retString; } @Transactional(readOnly = true) public SearchResultValue[] searchWeb(Integer siteId, final String searchItem, Integer pageSize, Integer pageNumber, Map safeGuardCookieMap) throws Exception { return searchWeb(siteId, searchItem, pageSize, pageNumber, safeGuardCookieMap, null); } public SearchResultValue[] searchWeb(Integer siteId, final String searchItem, Integer pageSize, Integer pageNumber, Map safeGuardCookieMap, String searchUrl) throws Exception { if (pageSize != null && pageSize.intValue() <= 1) pageSize = new Integer(20); if (pageNumber != null && pageNumber.intValue() < 0) pageNumber = new Integer(0); // first page SearchResultValue[] staticRetArr = null; Vector<SearchResultValue> retArr = new Vector<SearchResultValue>(); if (log.isDebugEnabled()) log.debug("starting compass-search"); try { if (log.isDebugEnabled()) { log.debug("search for: \"" + searchItem + "\""); } //TODO: find calls of searchWeb and ADD exception handling //special chars with a meaning in Lucene have to be escaped - there is a mechanism for //that in Lucene - QueryParser.escape but I don't want to replace '*','?','+','-' in searchItem String searchItemEsc = LUCENE_PATTERN.matcher(searchItem).replaceAll(REPLACEMENT_STRING); String searchUrlEsc = null; if (searchUrl != null) { searchUrlEsc = LUCENE_PATTERN.matcher(searchUrl).replaceAll(REPLACEMENT_STRING); } if (log.isDebugEnabled() && !searchItem.equalsIgnoreCase(searchItemEsc)) { log.debug("search for(escaped form): \"" + searchItemEsc + "\""); } CompassSession session = compass.openSession(); //per default searchItems get connected by AND (compare CompassSettings.java) CompassQuery query = buildRatedWildcardQuery(session, siteId, searchItemEsc, searchUrlEsc); if (log.isDebugEnabled()) { log.debug("search for query: " + query.toString()); } CompassSearchHelper searchHelper = new CompassSearchHelper(compass, pageSize) { @Override protected void doProcessBeforeDetach(CompassSearchCommand searchCommand, CompassSession session, CompassHits hits, int from, int size) { for (int i = 0; i < hits.length(); i++) { hits.highlighter(i).fragment("contents"); } } }; CompassSearchCommand command = null; if (pageSize == null) { command = new CompassSearchCommand(query); } else { command = new CompassSearchCommand(query, pageNumber); } CompassSearchResults results = searchHelper.search(command); if (log.isDebugEnabled()) log.debug("search lasted " + results.getSearchTime() + " milliseconds"); CompassHit[] hits = results.getHits(); for (int i = 0; i < hits.length; i++) { String alias = hits[i].getAlias(); Resource resource = hits[i].getResource(); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { - Integer vcId = Integer.getInteger(resource.getProperty("viewComponentId").getStringValue()); - if (safeguardServiceSpring.isSafeguardAuthenticationNeeded(vcId, safeGuardCookieMap)) { - continue; + try { + Integer vcId = Integer.getInteger(resource.getProperty("viewComponentId").getStringValue()); + if (safeguardServiceSpring.isSafeguardAuthenticationNeeded(vcId, safeGuardCookieMap)) { + continue; + } + } catch (Exception e) { + if (log.isDebugEnabled()) log.debug("Error in compas result filtering - " + e.getMessage(), e); } } SearchResultValue retVal = new SearchResultValue(); retVal.setScore((int) (hits[i].getScore() * 100.0f)); //CompassHighlightedText text = hits[i].getHighlightedText(); retVal.setSummary(stripNonValidXMLCharacters(hits[i].getHighlightedText().getHighlightedText("contents"))); retVal.setUnitId(new Integer(resource.getProperty("unitId").getStringValue())); retVal.setUnitName(resource.getProperty("unitName").getStringValue()); retVal.setPageSize(pageSize); retVal.setPageNumber(pageNumber); retVal.setDuration(Long.valueOf(results.getSearchTime())); if (results.getPages() != null) { retVal.setPageAmount(Integer.valueOf(results.getPages().length)); } else { retVal.setPageAmount(new Integer(1)); } retVal.setTotalHits(Integer.valueOf(results.getTotalHits())); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { String url = resource.getProperty("url").getStringValue(); if (url != null) { retVal.setUrl(url); retVal.setTitle(resource.getProperty("title").getStringValue()); retVal.setLanguage(resource.getProperty("language").getStringValue()); retVal.setViewType(resource.getProperty("viewtype").getStringValue()); Property template = resource.getProperty("template"); retVal.setTemplate(template != null ? template.getStringValue() : "standard"); } } else { String documentId = resource.getProperty("documentId").getStringValue(); Integer docId = null; try { docId = Integer.valueOf(documentId); } catch (Exception e) { log.warn("Error converting documentId: " + e.getMessage()); if (log.isDebugEnabled()) log.debug(e); } if (docId != null) { retVal.setDocumentId(docId); retVal.setDocumentName(resource.getProperty("documentName").getStringValue()); retVal.setMimeType(resource.getProperty("mimeType").getStringValue()); retVal.setTimeStamp(resource.getProperty("timeStamp").getStringValue()); } } retArr.add(retVal); } } catch (BooleanQuery.TooManyClauses tmc) { StringBuffer sb = new StringBuffer(256); sb.append("BooleanQuery.TooManyClauses Exception. "); sb.append("This typically happens if a PrefixQuery, FuzzyQuery, WildcardQuery, or RangeQuery is expanded to many terms during search. "); sb.append("Possible solution: BooleanQuery.setMaxClauseCount() > 1024(default)"); sb.append(" or reform the search querry with more letters and less wildcards (*)."); log.error(sb.toString(), tmc); //Exception gets thrown again to allow the caller to react throw tmc; } catch (Exception e) { log.error("Error performing search with compass: " + e.getMessage(), e); } if (log.isDebugEnabled()) log.debug("finished compass-search"); staticRetArr = new SearchResultValue[retArr.size()]; retArr.toArray(staticRetArr); return staticRetArr; } public String stripNonValidXMLCharacters(String in) { if (in == null) return ""; String stripped = in.replaceAll("[^\\u0009\\u000a\\u000d\\u0020-\\ud7ff\\e0000-\\ufffd]", ""); return stripped; } @SuppressWarnings("unchecked") private CompassQuery buildRatedWildcardQuery(CompassSession session, Integer siteId, String searchItem, String searchUrl) throws IOException, ParseException, InstantiationException, IllegalAccessException, ClassNotFoundException { Analyzer analyzer = null; CompassBooleanQueryBuilder queryBuilder = session.queryBuilder().bool(); IndexReader ir = LuceneHelper.getLuceneInternalSearch(session).getReader(); Query query; QueryParser parser; try { String analyzerClass = session.getSettings().getSetting("compass.engine.analyzer.search.type"); Constructor<Analyzer> analyzerConstructor = (Constructor<Analyzer>) (Class.forName(analyzerClass)).getConstructor(); analyzer = analyzerConstructor.newInstance(); if (log.isInfoEnabled()) log.info("Created search analyzer from compass settings - class is: " + analyzer.getClass().getName()); } catch (Exception e) { log.error("Error while instantiating search analyzer from compass settings - going on with StandardAnalyzer"); analyzer = new StandardAnalyzer(); } if (searchUrl != null) { if (log.isDebugEnabled()) log.debug("to search all hosts and subpages attaching * at start and end of urlString..."); // search on this side and all sub sites on all hosts searchUrl = "*" + searchUrl + "*"; if (log.isDebugEnabled()) log.debug("urlString before parsing: " + searchUrl); parser = new QueryParser("url", analyzer); parser.setAllowLeadingWildcard(true); query = parser.parse(searchUrl).rewrite(ir); queryBuilder.addMust(LuceneHelper.createCompassQuery(session, query)); } query = new QueryParser("siteId", analyzer).parse(siteId.toString()); queryBuilder.addMust(LuceneHelper.createCompassQuery(session, query)); CompassBooleanQueryBuilder subQueryBuilder = session.queryBuilder().bool(); String searchFields[] = {"metadata", "url", "title", "contents"}; for (int i = 0; i < searchFields.length; i++) { if (i == (searchFields.length - 1) && searchUrl != null) { searchItem = searchItem + " " + searchUrl; } parser = new QueryParser(searchFields[i], analyzer); parser.setAllowLeadingWildcard(true); query = parser.parse(searchItem); query = query.rewrite(ir); query.setBoost(searchFields.length - i); subQueryBuilder.addShould(LuceneHelper.createCompassQuery(session, query)); } queryBuilder.addMust(subQueryBuilder.toQuery()); return queryBuilder.toQuery(); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void indexPage(Integer contentId) { ContentHbm content = getContentHbmDao().load(contentId); ContentVersionHbm contentVersion = content.getLastContentVersion(); if (contentVersion == null) { // liveserver?! contentVersion = content.getContentVersionForPublish(); } if (contentVersion == null) { log.error("ContentVersion not existing for content: " + content.getContentId()); return; } String contentText = contentVersion.getText(); Collection vclColl = getViewComponentHbmDao().findByReferencedContent(content.getContentId().toString()); Iterator it = vclColl.iterator(); while (it.hasNext()) { ViewComponentHbm viewComponent = (ViewComponentHbm) it.next(); if (log.isDebugEnabled()) log.debug("Updating Indexes for VCID " + viewComponent.getDisplayLinkName()); if (viewComponent.isSearchIndexed()) { this.indexPage4Lucene(viewComponent, contentText); } else { searchengineDeleteService.deletePage4Lucene(viewComponent); } if (viewComponent.isXmlSearchIndexed()) { this.indexPage4Xml(viewComponent, contentText); } else { searchengineDeleteService.deletePage4Xml(viewComponent); } Collection referencingViewComponents = getViewComponentHbmDao().findByReferencedViewComponent(viewComponent.getViewComponentId().toString()); Iterator itRef = referencingViewComponents.iterator(); while (itRef.hasNext()) { ViewComponentHbm refViewComponent = (ViewComponentHbm) itRef.next(); if (refViewComponent.getViewType() == Constants.VIEW_TYPE_SYMLINK) { // acts as normal content if (log.isDebugEnabled()) log.debug("trying to index symLink " + refViewComponent.getDisplayLinkName()); if (refViewComponent.isSearchIndexed()) { this.indexPage4Lucene(refViewComponent, contentText); } else { searchengineDeleteService.deletePage4Lucene(refViewComponent); } if (refViewComponent.isXmlSearchIndexed()) { this.indexPage4Xml(refViewComponent, contentText); } else { searchengineDeleteService.deletePage4Xml(refViewComponent); } } /* Die Referenzen im Tree KÖNNEN nur über "findByReferencedViewComponent" gefunden werden, und nicht über die XML Suchmaschine. */ } } content.setUpdateSearchIndex(false); } private void indexPage4Lucene(ViewComponentHbm viewComponent, String contentText) { if (log.isDebugEnabled()) log.debug("Lucene-Index create / update for VC " + viewComponent.getViewComponentId()); ViewDocumentHbm vdl = viewComponent.getViewDocument(); CompassSession session = null; CompassTransaction tx = null; File file = null; try { String currentUrl = searchengineDeleteService.getUrl(viewComponent); file = this.downloadFile(currentUrl); if (file != null) { String cleanUrl = viewComponent.getViewDocument().getSite().getPageNameSearch(); cleanUrl = currentUrl.substring(0, currentUrl.length() - cleanUrl.length()); session = compass.openSession(); Resource resource = htmlResourceLocator.getResource(session, file, cleanUrl, new Date(System.currentTimeMillis()), viewComponent, vdl); tx = session.beginTransaction(); session.save(resource); tx.commit(); session.close(); session = null; } else { log.warn("Critical Error during indexPage4Lucene - cound not find Ressource: " + currentUrl); } } catch (Exception e) { log.warn("Error indexPage4Lucene, VCID " + viewComponent.getViewComponentId().toString() + ": " + e.getMessage(), e); if (tx != null) tx.rollback(); } finally { if (session != null) session.close(); //delete temp file if (file != null) { file.delete(); } } if (log.isDebugEnabled()) log.debug("finished indexPage4Lucene"); } private void indexPage4Xml(ViewComponentHbm viewComponent, String contentText) { if (log.isDebugEnabled()) log.debug("XML-Index create / update for VC " + viewComponent.getViewComponentId()); ViewDocumentHbm vdl = viewComponent.getViewDocument(); SiteHbm site = vdl.getSite(); org.w3c.dom.Document wdoc = null; try { wdoc = XercesHelper.string2Dom(contentText); } catch (Throwable t) { } if (wdoc != null) { HashMap<String, String> metaAttributes = new HashMap<String, String>(); if (log.isDebugEnabled()) { log.debug("SearchUpdateMessageBeanImpl.indexVC(...) -> infoText = " + viewComponent.getLinkDescription()); log.debug("SearchUpdateMessageBeanImpl.indexVC(...) -> text = " + viewComponent.getDisplayLinkName()); log.debug("SearchUpdateMessageBeanImpl.indexVC(...) -> unitId = " + viewComponent.getUnit4ViewComponent()); } metaAttributes.put("infoText", viewComponent.getLinkDescription()); metaAttributes.put("text", viewComponent.getDisplayLinkName()); metaAttributes.put("unitId", (viewComponent.getUnit4ViewComponent() == null ? "" : viewComponent.getUnit4ViewComponent().toString())); xmlDb.saveXml(site.getSiteId(), viewComponent.getViewComponentId(), contentText, metaAttributes); } if (log.isDebugEnabled()) log.debug("finished indexPage4Xml"); } private File downloadFile(String strUrl) { try { File file = File.createTempFile("indexingTempFile", "html"); file.deleteOnExit(); client.getParams().setConnectionManagerTimeout(20000); HttpMethod method = new GetMethod(strUrl); method.setFollowRedirects(true); method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); for (int i = 0; i <= 3; i++) { if (i == 3) { log.error("Trying to fetch the URL " + strUrl + " three times with no success - page could not be loaded in searchengine!"); break; } if (log.isDebugEnabled()) log.debug("Trying " + i + " to catch the URL"); if (this.downloadToFile(method, file, strUrl)) { if (log.isDebugEnabled()) log.debug("got it!"); break; } } if (log.isDebugEnabled()) log.debug("downloadFile: FINISHED"); return file; } catch (Exception exe) { return null; } } private boolean downloadToFile(HttpMethod method, File file, String strUrl) { boolean retVal = false; try { client.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); OutputStream out = new FileOutputStream(file); try { byte[] buf = new byte[2048]; for (;;) { int cb = in.read(buf); if (cb < 0) break; out.write(buf, 0, cb); } } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } } retVal = true; } catch (HttpException he) { log.error("Http error connecting to '" + strUrl + "'"); log.error(he.getMessage()); } catch (IOException ioe) { log.error("Unable to connect to '" + strUrl + "'"); } //clean up the connection resources method.releaseConnection(); return retVal; } @Transactional(propagation = Propagation.REQUIRES_NEW) public void indexDocument(Integer documentId) { if (log.isDebugEnabled()) { log.debug("Index create / update for Document: " + documentId); } DocumentHbm document = getDocumentHbmDao().load(documentId); if (log.isDebugEnabled()) { log.debug("Document " + document.getDocumentId() + " \"" + document.getDocumentName() + "\" \"" + document.getMimeType()); } if (!documentResourceLocatorFactory.isSupportedFileFormat(document.getMimeType())) { if (log.isInfoEnabled()) log.info("Document " + document.getDocumentId() + " \"" + document.getDocumentName() + "\" \"" + document.getMimeType() + "\" is not supported, skipping..."); document.setUpdateSearchIndex(false); return; } CompassSession session = null; CompassTransaction tx = null; try { session = compass.openSession(); Resource resource = documentResourceLocatorFactory.getResource(session, document); tx = session.beginTransaction(); session.save(resource); tx.commit(); session.close(); session = null; } catch (Exception e) { log.warn("Error indexDocument " + document.getDocumentId().toString() + ": " + e.getMessage()); if (tx != null) tx.rollback(); } finally { document.setUpdateSearchIndex(false); if (session != null) session.close(); } if (log.isInfoEnabled()) log.info("finished indexDocument " + document.getDocumentId() + " \"" + document.getDocumentName() + "\""); } }
true
true
public SearchResultValue[] searchWeb(Integer siteId, final String searchItem, Integer pageSize, Integer pageNumber, Map safeGuardCookieMap, String searchUrl) throws Exception { if (pageSize != null && pageSize.intValue() <= 1) pageSize = new Integer(20); if (pageNumber != null && pageNumber.intValue() < 0) pageNumber = new Integer(0); // first page SearchResultValue[] staticRetArr = null; Vector<SearchResultValue> retArr = new Vector<SearchResultValue>(); if (log.isDebugEnabled()) log.debug("starting compass-search"); try { if (log.isDebugEnabled()) { log.debug("search for: \"" + searchItem + "\""); } //TODO: find calls of searchWeb and ADD exception handling //special chars with a meaning in Lucene have to be escaped - there is a mechanism for //that in Lucene - QueryParser.escape but I don't want to replace '*','?','+','-' in searchItem String searchItemEsc = LUCENE_PATTERN.matcher(searchItem).replaceAll(REPLACEMENT_STRING); String searchUrlEsc = null; if (searchUrl != null) { searchUrlEsc = LUCENE_PATTERN.matcher(searchUrl).replaceAll(REPLACEMENT_STRING); } if (log.isDebugEnabled() && !searchItem.equalsIgnoreCase(searchItemEsc)) { log.debug("search for(escaped form): \"" + searchItemEsc + "\""); } CompassSession session = compass.openSession(); //per default searchItems get connected by AND (compare CompassSettings.java) CompassQuery query = buildRatedWildcardQuery(session, siteId, searchItemEsc, searchUrlEsc); if (log.isDebugEnabled()) { log.debug("search for query: " + query.toString()); } CompassSearchHelper searchHelper = new CompassSearchHelper(compass, pageSize) { @Override protected void doProcessBeforeDetach(CompassSearchCommand searchCommand, CompassSession session, CompassHits hits, int from, int size) { for (int i = 0; i < hits.length(); i++) { hits.highlighter(i).fragment("contents"); } } }; CompassSearchCommand command = null; if (pageSize == null) { command = new CompassSearchCommand(query); } else { command = new CompassSearchCommand(query, pageNumber); } CompassSearchResults results = searchHelper.search(command); if (log.isDebugEnabled()) log.debug("search lasted " + results.getSearchTime() + " milliseconds"); CompassHit[] hits = results.getHits(); for (int i = 0; i < hits.length; i++) { String alias = hits[i].getAlias(); Resource resource = hits[i].getResource(); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { Integer vcId = Integer.getInteger(resource.getProperty("viewComponentId").getStringValue()); if (safeguardServiceSpring.isSafeguardAuthenticationNeeded(vcId, safeGuardCookieMap)) { continue; } } SearchResultValue retVal = new SearchResultValue(); retVal.setScore((int) (hits[i].getScore() * 100.0f)); //CompassHighlightedText text = hits[i].getHighlightedText(); retVal.setSummary(stripNonValidXMLCharacters(hits[i].getHighlightedText().getHighlightedText("contents"))); retVal.setUnitId(new Integer(resource.getProperty("unitId").getStringValue())); retVal.setUnitName(resource.getProperty("unitName").getStringValue()); retVal.setPageSize(pageSize); retVal.setPageNumber(pageNumber); retVal.setDuration(Long.valueOf(results.getSearchTime())); if (results.getPages() != null) { retVal.setPageAmount(Integer.valueOf(results.getPages().length)); } else { retVal.setPageAmount(new Integer(1)); } retVal.setTotalHits(Integer.valueOf(results.getTotalHits())); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { String url = resource.getProperty("url").getStringValue(); if (url != null) { retVal.setUrl(url); retVal.setTitle(resource.getProperty("title").getStringValue()); retVal.setLanguage(resource.getProperty("language").getStringValue()); retVal.setViewType(resource.getProperty("viewtype").getStringValue()); Property template = resource.getProperty("template"); retVal.setTemplate(template != null ? template.getStringValue() : "standard"); } } else { String documentId = resource.getProperty("documentId").getStringValue(); Integer docId = null; try { docId = Integer.valueOf(documentId); } catch (Exception e) { log.warn("Error converting documentId: " + e.getMessage()); if (log.isDebugEnabled()) log.debug(e); } if (docId != null) { retVal.setDocumentId(docId); retVal.setDocumentName(resource.getProperty("documentName").getStringValue()); retVal.setMimeType(resource.getProperty("mimeType").getStringValue()); retVal.setTimeStamp(resource.getProperty("timeStamp").getStringValue()); } } retArr.add(retVal); } } catch (BooleanQuery.TooManyClauses tmc) { StringBuffer sb = new StringBuffer(256); sb.append("BooleanQuery.TooManyClauses Exception. "); sb.append("This typically happens if a PrefixQuery, FuzzyQuery, WildcardQuery, or RangeQuery is expanded to many terms during search. "); sb.append("Possible solution: BooleanQuery.setMaxClauseCount() > 1024(default)"); sb.append(" or reform the search querry with more letters and less wildcards (*)."); log.error(sb.toString(), tmc); //Exception gets thrown again to allow the caller to react throw tmc; } catch (Exception e) { log.error("Error performing search with compass: " + e.getMessage(), e); } if (log.isDebugEnabled()) log.debug("finished compass-search"); staticRetArr = new SearchResultValue[retArr.size()]; retArr.toArray(staticRetArr); return staticRetArr; }
public SearchResultValue[] searchWeb(Integer siteId, final String searchItem, Integer pageSize, Integer pageNumber, Map safeGuardCookieMap, String searchUrl) throws Exception { if (pageSize != null && pageSize.intValue() <= 1) pageSize = new Integer(20); if (pageNumber != null && pageNumber.intValue() < 0) pageNumber = new Integer(0); // first page SearchResultValue[] staticRetArr = null; Vector<SearchResultValue> retArr = new Vector<SearchResultValue>(); if (log.isDebugEnabled()) log.debug("starting compass-search"); try { if (log.isDebugEnabled()) { log.debug("search for: \"" + searchItem + "\""); } //TODO: find calls of searchWeb and ADD exception handling //special chars with a meaning in Lucene have to be escaped - there is a mechanism for //that in Lucene - QueryParser.escape but I don't want to replace '*','?','+','-' in searchItem String searchItemEsc = LUCENE_PATTERN.matcher(searchItem).replaceAll(REPLACEMENT_STRING); String searchUrlEsc = null; if (searchUrl != null) { searchUrlEsc = LUCENE_PATTERN.matcher(searchUrl).replaceAll(REPLACEMENT_STRING); } if (log.isDebugEnabled() && !searchItem.equalsIgnoreCase(searchItemEsc)) { log.debug("search for(escaped form): \"" + searchItemEsc + "\""); } CompassSession session = compass.openSession(); //per default searchItems get connected by AND (compare CompassSettings.java) CompassQuery query = buildRatedWildcardQuery(session, siteId, searchItemEsc, searchUrlEsc); if (log.isDebugEnabled()) { log.debug("search for query: " + query.toString()); } CompassSearchHelper searchHelper = new CompassSearchHelper(compass, pageSize) { @Override protected void doProcessBeforeDetach(CompassSearchCommand searchCommand, CompassSession session, CompassHits hits, int from, int size) { for (int i = 0; i < hits.length(); i++) { hits.highlighter(i).fragment("contents"); } } }; CompassSearchCommand command = null; if (pageSize == null) { command = new CompassSearchCommand(query); } else { command = new CompassSearchCommand(query, pageNumber); } CompassSearchResults results = searchHelper.search(command); if (log.isDebugEnabled()) log.debug("search lasted " + results.getSearchTime() + " milliseconds"); CompassHit[] hits = results.getHits(); for (int i = 0; i < hits.length; i++) { String alias = hits[i].getAlias(); Resource resource = hits[i].getResource(); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { try { Integer vcId = Integer.getInteger(resource.getProperty("viewComponentId").getStringValue()); if (safeguardServiceSpring.isSafeguardAuthenticationNeeded(vcId, safeGuardCookieMap)) { continue; } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Error in compas result filtering - " + e.getMessage(), e); } } SearchResultValue retVal = new SearchResultValue(); retVal.setScore((int) (hits[i].getScore() * 100.0f)); //CompassHighlightedText text = hits[i].getHighlightedText(); retVal.setSummary(stripNonValidXMLCharacters(hits[i].getHighlightedText().getHighlightedText("contents"))); retVal.setUnitId(new Integer(resource.getProperty("unitId").getStringValue())); retVal.setUnitName(resource.getProperty("unitName").getStringValue()); retVal.setPageSize(pageSize); retVal.setPageNumber(pageNumber); retVal.setDuration(Long.valueOf(results.getSearchTime())); if (results.getPages() != null) { retVal.setPageAmount(Integer.valueOf(results.getPages().length)); } else { retVal.setPageAmount(new Integer(1)); } retVal.setTotalHits(Integer.valueOf(results.getTotalHits())); if ("HtmlSearchValue".equalsIgnoreCase(alias)) { String url = resource.getProperty("url").getStringValue(); if (url != null) { retVal.setUrl(url); retVal.setTitle(resource.getProperty("title").getStringValue()); retVal.setLanguage(resource.getProperty("language").getStringValue()); retVal.setViewType(resource.getProperty("viewtype").getStringValue()); Property template = resource.getProperty("template"); retVal.setTemplate(template != null ? template.getStringValue() : "standard"); } } else { String documentId = resource.getProperty("documentId").getStringValue(); Integer docId = null; try { docId = Integer.valueOf(documentId); } catch (Exception e) { log.warn("Error converting documentId: " + e.getMessage()); if (log.isDebugEnabled()) log.debug(e); } if (docId != null) { retVal.setDocumentId(docId); retVal.setDocumentName(resource.getProperty("documentName").getStringValue()); retVal.setMimeType(resource.getProperty("mimeType").getStringValue()); retVal.setTimeStamp(resource.getProperty("timeStamp").getStringValue()); } } retArr.add(retVal); } } catch (BooleanQuery.TooManyClauses tmc) { StringBuffer sb = new StringBuffer(256); sb.append("BooleanQuery.TooManyClauses Exception. "); sb.append("This typically happens if a PrefixQuery, FuzzyQuery, WildcardQuery, or RangeQuery is expanded to many terms during search. "); sb.append("Possible solution: BooleanQuery.setMaxClauseCount() > 1024(default)"); sb.append(" or reform the search querry with more letters and less wildcards (*)."); log.error(sb.toString(), tmc); //Exception gets thrown again to allow the caller to react throw tmc; } catch (Exception e) { log.error("Error performing search with compass: " + e.getMessage(), e); } if (log.isDebugEnabled()) log.debug("finished compass-search"); staticRetArr = new SearchResultValue[retArr.size()]; retArr.toArray(staticRetArr); return staticRetArr; }
diff --git a/PlayersInCubes/src/me/asofold/bukkit/pic/core/PicCore.java b/PlayersInCubes/src/me/asofold/bukkit/pic/core/PicCore.java index e40f870..899bd12 100644 --- a/PlayersInCubes/src/me/asofold/bukkit/pic/core/PicCore.java +++ b/PlayersInCubes/src/me/asofold/bukkit/pic/core/PicCore.java @@ -1,315 +1,314 @@ package me.asofold.bukkit.pic.core; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import me.asofold.bukkit.pic.config.Settings; import me.asofold.bukkit.pic.stats.Stats; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; /** * Core functionality. * @author mc_dev * */ public final class PicCore{ static final Stats stats = new Stats("[PIC]"); static final Integer idPPCubes = stats.getNewId("pp_ncubes"); static final Integer idPPRemCubes= stats.getNewId("pp_remcubes"); static final Integer idPPSeen = stats.getNewId("pp_insight"); static final Integer idPPRemove = stats.getNewId("pp_offsight"); /** * Settings. */ private Settings settings = new Settings(); /** * World specific CubeServer. Every world must have one to keep track of players inside of worlds. */ private final Map<String, CubeServer> cubeServers = new HashMap<String, CubeServer>(53); /** * Player specific data / lookup. */ private final Map<String, PicPlayer> players = new HashMap<String, PicPlayer>(517); private File dataFolder = null; private boolean enabled = true; public final void setDataFolder(final File dataFolder) { this.dataFolder = dataFolder; } private final void applySettings(final Settings settings) { // Later: maybe try for a lazy transition or a hard one depending on changes. this.settings = settings; cleanup(); enabled = settings.enabled; } public Settings getSettings(){ return settings; } public final boolean reload() { final File file = new File(dataFolder, "config.yml"); final Settings settings = Settings.load(file); if (settings != null){ applySettings(settings); // Consider logging that settings were reloaded. return true; } else return false; } /** * This will alter and save the settings, unless no change is done. * @param enabled * @return If this was a state change. */ public final boolean setEnabled(final boolean enabled) { File file = new File(dataFolder, "config.yml"); if (!(enabled ^ this.enabled)){ if (!file.exists()) settings.save(file); return false; } this.enabled = enabled; if (enabled) checkAllOnlinePlayers(); else clear(false); // Renders all visible. settings.enabled = enabled; settings.save(file); return true; } public final boolean isEnabled(){ return enabled; } public final Stats getStats(){ return stats; } /** * Get the cube server for the world, will create it if not yet existent. * @param world Exact case. * @return */ private final CubeServer getCubeServer(final String world) { CubeServer server = cubeServers.get(world); if (server == null){ server = new CubeServer(world, this, settings.cubeSize); cubeServers.put(world, server); } return server; } /** * Get PicPlayer, put to internals, if not present. * @param player * @return */ private final PicPlayer getPicPlayer(final Player player){ final String name = player.getName(); final PicPlayer pp = players.get(name); if (pp != null) return pp; final PicPlayer npp = new PicPlayer(player); players.put(name, npp); return npp; } public final void renderBlind(final PicPlayer pp, final Collection<String> names) { final Player player = pp.bPlayer; for (final String name : names){ final PicPlayer opp = players.get(name); // if (opp == null) continue; // ERROR if (player.canSee(opp.bPlayer)) player.hidePlayer(opp.bPlayer); if (opp.bPlayer.canSee(player)) opp.bPlayer.hidePlayer(player); } } public final void renderSeen(final PicPlayer pp, final Collection<String> names) { final Player player = pp.bPlayer; for (final String name : names){ final PicPlayer opp = players.get(name); // if (opp == null) continue; // ERROR if (!player.canSee(opp.bPlayer)) player.showPlayer(opp.bPlayer); if (!opp.bPlayer.canSee(player)) opp.bPlayer.showPlayer(player); } } /** * Remove all players, remove all data, check in all players again. */ public final void cleanup() { clear(true); checkAllOnlinePlayers(); } public final void clear(final boolean blind){ removeAllPlayers(blind); for (final CubeServer server : cubeServers.values()){ server.clear(); } cubeServers.clear(); } /** * Quit, kick. * @param player */ public final void checkOut(final Player player) { if (!enabled) return; final String playerName = player.getName(); final PicPlayer pp = players.get(playerName); if (pp == null){ // contract ? for (final PicPlayer opp : players.values()){ if (opp.playerName.equals(playerName)) continue; if (opp.bPlayer.canSee(player)) opp.bPlayer.hidePlayer(player); if (player.canSee(opp.bPlayer)) player.hidePlayer(opp.bPlayer); } } else{ if (pp.world != null) getCubeServer(pp.world).players.remove(player); renderBlind(pp, pp.checkOut()); players.remove(pp.playerName); // TODO: maybe hold data longer. } } /** * Does currently not remove players from the CubeServer players sets. * @param blind Render players blind or let all see all again (very expensive). */ private final void removeAllPlayers(final boolean blind) { if (blind){ // "Efficient" way: only render those blind, that are seen. for (final PicPlayer pp : players.values()){ renderBlind(pp, pp.checkOut()); } } else{ // Costly: basically quadratic time all vs. all. final Player[] online = Bukkit.getOnlinePlayers(); for (final PicPlayer pp : players.values()){ pp.checkOut(); // Ignore return value. for (final Player other : online){ if (!other.canSee(pp.bPlayer)) other.showPlayer(pp.bPlayer); if (!pp.bPlayer.canSee(other)) pp.bPlayer.showPlayer(other); } } } players.clear(); } /** * Join or respawn. * @param player * @param location */ public final void checkIn(final Player player, Location location) { checkOut(player); check(player, player.getLocation()); } public final void checkAllOnlinePlayers() { if (!enabled) return; for (final Player player : Bukkit.getOnlinePlayers()){ check(player, player.getLocation()); } } /** * Lighter check: Use this for set up players. * @param player * @param to NOT NULL */ public final void check(final Player player, final Location to) { if (!enabled) return; final PicPlayer pp = getPicPlayer(player); final String world = to.getWorld().getName(); if (settings.ignoreWorlds.contains(world)){ // Moving in a ignored world. if (pp.world == null){ // New data. } else if (world.equals(pp.world)){ // Already inside, no changes. return; } else{ // World change. getCubeServer(pp.world).players.remove(player); if (!settings.ignoreWorlds.contains(pp.world)){ // Old world was checked. pp.checkOut(); } } // World change or new. final CubeServer server = getCubeServer(world); if (!server.players.isEmpty()) renderSeen(pp, server.players); - renderSeen(pp, server.players); // TODO: Correct here ? server.players.add(pp.playerName); pp.world = world; pp.tsLoc = 0; // necessary. // else: keep ignoring. return; } final int x = to.getBlockX(); final int y = to.getBlockY(); final int z = to.getBlockZ(); final long ts = System.currentTimeMillis(); // Check if to set the position: if (!world.equals(pp.world)){ // World change into a checked world. // Add to new CubeServer: final CubeServer server = getCubeServer(world); - renderBlind(pp, server.players); + if (!server.players.isEmpty()) renderBlind(pp, server.players); server.players.add(pp.playerName); // Check removal: if (pp.world == null){ // Was a new player. } else{ // Remove from old server (light). getCubeServer(pp.world).players.remove(pp.playerName); pp.checkOut(); } } else if (settings.durExpireData > 0 && ts - pp.tsLoc > settings.durExpireData){ // Expired, set new (no world change). } else if (pp.inRange(x, y, z, settings.distLazy)){ // Still in range, quick return (no world change). return; } else{ // Out of range set new (no world change). } // Set position. pp.tsLoc = ts; pp.world = world; pp.x = x; pp.y = y; pp.z = z; // Add player to all cubes ! getCubeServer(world).update(pp, settings.distCube); } }
false
true
public final void check(final Player player, final Location to) { if (!enabled) return; final PicPlayer pp = getPicPlayer(player); final String world = to.getWorld().getName(); if (settings.ignoreWorlds.contains(world)){ // Moving in a ignored world. if (pp.world == null){ // New data. } else if (world.equals(pp.world)){ // Already inside, no changes. return; } else{ // World change. getCubeServer(pp.world).players.remove(player); if (!settings.ignoreWorlds.contains(pp.world)){ // Old world was checked. pp.checkOut(); } } // World change or new. final CubeServer server = getCubeServer(world); if (!server.players.isEmpty()) renderSeen(pp, server.players); renderSeen(pp, server.players); // TODO: Correct here ? server.players.add(pp.playerName); pp.world = world; pp.tsLoc = 0; // necessary. // else: keep ignoring. return; } final int x = to.getBlockX(); final int y = to.getBlockY(); final int z = to.getBlockZ(); final long ts = System.currentTimeMillis(); // Check if to set the position: if (!world.equals(pp.world)){ // World change into a checked world. // Add to new CubeServer: final CubeServer server = getCubeServer(world); renderBlind(pp, server.players); server.players.add(pp.playerName); // Check removal: if (pp.world == null){ // Was a new player. } else{ // Remove from old server (light). getCubeServer(pp.world).players.remove(pp.playerName); pp.checkOut(); } } else if (settings.durExpireData > 0 && ts - pp.tsLoc > settings.durExpireData){ // Expired, set new (no world change). } else if (pp.inRange(x, y, z, settings.distLazy)){ // Still in range, quick return (no world change). return; } else{ // Out of range set new (no world change). } // Set position. pp.tsLoc = ts; pp.world = world; pp.x = x; pp.y = y; pp.z = z; // Add player to all cubes ! getCubeServer(world).update(pp, settings.distCube); }
public final void check(final Player player, final Location to) { if (!enabled) return; final PicPlayer pp = getPicPlayer(player); final String world = to.getWorld().getName(); if (settings.ignoreWorlds.contains(world)){ // Moving in a ignored world. if (pp.world == null){ // New data. } else if (world.equals(pp.world)){ // Already inside, no changes. return; } else{ // World change. getCubeServer(pp.world).players.remove(player); if (!settings.ignoreWorlds.contains(pp.world)){ // Old world was checked. pp.checkOut(); } } // World change or new. final CubeServer server = getCubeServer(world); if (!server.players.isEmpty()) renderSeen(pp, server.players); server.players.add(pp.playerName); pp.world = world; pp.tsLoc = 0; // necessary. // else: keep ignoring. return; } final int x = to.getBlockX(); final int y = to.getBlockY(); final int z = to.getBlockZ(); final long ts = System.currentTimeMillis(); // Check if to set the position: if (!world.equals(pp.world)){ // World change into a checked world. // Add to new CubeServer: final CubeServer server = getCubeServer(world); if (!server.players.isEmpty()) renderBlind(pp, server.players); server.players.add(pp.playerName); // Check removal: if (pp.world == null){ // Was a new player. } else{ // Remove from old server (light). getCubeServer(pp.world).players.remove(pp.playerName); pp.checkOut(); } } else if (settings.durExpireData > 0 && ts - pp.tsLoc > settings.durExpireData){ // Expired, set new (no world change). } else if (pp.inRange(x, y, z, settings.distLazy)){ // Still in range, quick return (no world change). return; } else{ // Out of range set new (no world change). } // Set position. pp.tsLoc = ts; pp.world = world; pp.x = x; pp.y = y; pp.z = z; // Add player to all cubes ! getCubeServer(world).update(pp, settings.distCube); }
diff --git a/triana-toolboxes/imageproc/src/main/java/imageproc/input/URLImage.java b/triana-toolboxes/imageproc/src/main/java/imageproc/input/URLImage.java index e89a7791..d0be83af 100644 --- a/triana-toolboxes/imageproc/src/main/java/imageproc/input/URLImage.java +++ b/triana-toolboxes/imageproc/src/main/java/imageproc/input/URLImage.java @@ -1,138 +1,139 @@ package imageproc.input; import org.trianacode.taskgraph.Unit; import org.trianacode.taskgraph.util.FileUtils; import triana.types.TrianaImage; import triana.types.TrianaPixelMap; import java.awt.*; /** * A URLImage unit which loads an image from a HTTP adddress * * @author Ian Taylor * @author Melanie Rhianna Lewis * @version 2.0 10 Aug 2000 */ public class URLImage extends Unit { String imageUrlString; /** * ********************************************* ** USER CODE of ImageLoader goes here *** * ********************************************* */ public void process() { TrianaImage trianaImage = null; Object data = getInputAtNode(0); if (data != null) { imageUrlString = data.toString(); } if (!imageUrlString.equals("")) { Image image = FileUtils.getImage(imageUrlString); trianaImage = new TrianaImage(image); } if (trianaImage == null) { - // ErrorDialog.show(null, getTask().getToolName() + ": " + Env.getString("ImageError")); + // ErrorDialog.show(null, getTask().getToolName() + ": " + Env.getString("ImageError")); //stop(); // stops the scheduler and hence this process! System.out.println("image error"); + notifyError("Image Error", new Throwable("Image Error")); } else { output(new TrianaPixelMap(trianaImage)); } } /** * Initialses information specific to ImageLoader. */ public void init() { super.init(); setDefaultInputNodes(1); setMinimumInputNodes(1); setMaximumInputNodes(Integer.MAX_VALUE); setDefaultOutputNodes(1); setMinimumOutputNodes(1); setMaximumOutputNodes(Integer.MAX_VALUE); imageUrlString = ""; } /** * Reset's ImageLoader */ public void reset() { super.reset(); } /** * Saves ImageLoader's parameters to the parameter file. */ // public void saveParameters() { // saveParameter("Url", imageUrlString); // } /** * Loads ImageLoader's parameters of from the parameter file. */ public void setParameter(String name, String value) { if (name.equals("Url")) { imageUrlString = value; } } /** * @return a string containing the names of the types allowed to be input to ImageLoader, each separated by a white * space. */ public String[] getInputTypes() { return new String[]{"java.lang.String"}; } /** * @return a string containing the names of the types output from Compare, each separated by a white space. */ public String[] getOutputTypes() { return new String[]{"triana.types.TrianaPixelMap"}; } /** * This returns a <b>brief!</b> description of what the unit does. The text here is shown in a pop up window when * the user puts the mouse over the unit icon for more than a second. */ public String getPopUpDescription() { return "Loads an image from a URL"; } /** * @returns the location of the help file for this unit. */ public String getHelpFile() { return "URLImage.html"; } // public void doubleClick() { // updateParameter("Url", Input.aString("Enter the URL of the GIF/JPEG file below :")); // } }
false
true
public void process() { TrianaImage trianaImage = null; Object data = getInputAtNode(0); if (data != null) { imageUrlString = data.toString(); } if (!imageUrlString.equals("")) { Image image = FileUtils.getImage(imageUrlString); trianaImage = new TrianaImage(image); } if (trianaImage == null) { // ErrorDialog.show(null, getTask().getToolName() + ": " + Env.getString("ImageError")); //stop(); // stops the scheduler and hence this process! System.out.println("image error"); } else { output(new TrianaPixelMap(trianaImage)); } }
public void process() { TrianaImage trianaImage = null; Object data = getInputAtNode(0); if (data != null) { imageUrlString = data.toString(); } if (!imageUrlString.equals("")) { Image image = FileUtils.getImage(imageUrlString); trianaImage = new TrianaImage(image); } if (trianaImage == null) { // ErrorDialog.show(null, getTask().getToolName() + ": " + Env.getString("ImageError")); //stop(); // stops the scheduler and hence this process! System.out.println("image error"); notifyError("Image Error", new Throwable("Image Error")); } else { output(new TrianaPixelMap(trianaImage)); } }
diff --git a/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java b/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java index 1880ead..57f1c54 100644 --- a/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java +++ b/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java @@ -1,251 +1,249 @@ /* * Copyright 2009 Sven Strickroth <[email protected]> * * This file is part of the SubmissionInterface. * * SubmissionInterface is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * SubmissionInterface is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SubmissionInterface. If not, see <http://www.gnu.org/licenses/>. */ package de.tuclausthal.submissioninterface.servlets.controller; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.hibernate.Session; import de.tuclausthal.submissioninterface.authfilter.SessionAdapter; import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory; import de.tuclausthal.submissioninterface.persistence.dao.ParticipationDAOIf; import de.tuclausthal.submissioninterface.persistence.dao.SubmissionDAOIf; import de.tuclausthal.submissioninterface.persistence.dao.TaskDAOIf; import de.tuclausthal.submissioninterface.persistence.dao.impl.LogDAO; import de.tuclausthal.submissioninterface.persistence.datamodel.Participation; import de.tuclausthal.submissioninterface.persistence.datamodel.ParticipationRole; import de.tuclausthal.submissioninterface.persistence.datamodel.Submission; import de.tuclausthal.submissioninterface.persistence.datamodel.Task; import de.tuclausthal.submissioninterface.persistence.datamodel.LogEntry.LogAction; import de.tuclausthal.submissioninterface.template.Template; import de.tuclausthal.submissioninterface.template.TemplateFactory; import de.tuclausthal.submissioninterface.util.ContextAdapter; import de.tuclausthal.submissioninterface.util.HibernateSessionHelper; import de.tuclausthal.submissioninterface.util.Util; /** * Controller-Servlet for the submission of files * @author Sven Strickroth */ public class SubmitSolution extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Session session = HibernateSessionHelper.getSession(); TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session); Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0)); if (task == null) { request.setAttribute("title", "Aufgabe nicht gefunden"); request.getRequestDispatcher("MessageView").forward(request, response); return; } // check Lecture Participation ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session); Participation participation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture()); if (participation == null) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights"); return; } if (task.getStart().after(Util.correctTimezone(new Date())) && participation.getRoleType().compareTo(ParticipationRole.TUTOR) < 0) { request.setAttribute("title", "Abgabe nicht gefunden"); request.getRequestDispatcher("MessageView").forward(request, response); return; } if (task.getDeadline().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) { request.setAttribute("title", "Abgabe nicht mehr m�glich"); request.getRequestDispatcher("MessageView").forward(request, response); return; } if (task.isShowTextArea() || "-".equals(task.getFilenameRegexp())) { String textsolution = ""; Submission submission = DAOFactory.SubmissionDAOIf(session).getSubmission(task, new SessionAdapter(request).getUser(session)); if (submission != null) { ContextAdapter contextAdapter = new ContextAdapter(getServletContext()); File textSolutionFile = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator") + "textloesung.txt"); if (textSolutionFile.exists()) { BufferedReader bufferedReader = new BufferedReader(new FileReader(textSolutionFile)); StringBuffer sb = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); sb.append(System.getProperty("line.separator")); } textsolution = sb.toString(); } } request.setAttribute("textsolution", textsolution); } request.setAttribute("task", task); request.getRequestDispatcher("SubmitSolutionFormView").forward(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Session session = HibernateSessionHelper.getSession(); Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session); Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0)); if (task == null) { template.printTemplateHeader("Aufgabe nicht gefunden"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } // check Lecture Participation ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session); Participation participation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture()); if (participation == null) { template.printTemplateHeader("Ung�ltige Anfrage"); out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>"); out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getStart().after(Util.correctTimezone(new Date())) && participation.getRoleType().compareTo(ParticipationRole.TUTOR) < 0) { template.printTemplateHeader("Aufgabe nicht abrufbar"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getDeadline().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) { template.printTemplateHeader("Abgabe nicht (mehr) m�glich"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session); Submission submission = submissionDAO.createSubmission(task, participation); ContextAdapter contextAdapter = new ContextAdapter(getServletContext()); File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator")); if (path.exists() == false) { path.mkdirs(); } //http://commons.apache.org/fileupload/using.html // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { if ("-".equals(task.getFilenameRegexp())) { request.setAttribute("title", "Dateiupload f�r diese Aufgabe deaktiviert."); request.getRequestDispatcher("MessageView").forward(request, response); return; } // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "filename invalid"); return; } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // Process a file upload if (!item.isFormField()) { Pattern pattern; if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty()) { - pattern = Pattern.compile("(\\|/)?([a-zA-Z0-9_.-])$"); + pattern = Pattern.compile(".*?(?:\\\\|/)?([a-zA-Z0-9_.-]+)$"); } else { - System.out.println(task.getFilenameRegexp()); - pattern = Pattern.compile("(\\|/)?(" + task.getFilenameRegexp() + ")$"); + pattern = Pattern.compile(".*?(?:\\\\|/)?(" + task.getFilenameRegexp() + ")$"); } - System.out.println(pattern.pattern() + " " + item.getName()); Matcher m = pattern.matcher(item.getName()); if (!m.matches()) { - out.println("Dateiname ung�ltig. Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt."); + out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt."); return; } - String fileName = m.group(0); + String fileName = m.group(1); File uploadedFile = new File(path, fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } submissionDAO.saveSubmission(submission); new LogDAO(session).createLogEntry(LogAction.UPLOAD, null, null); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } } } else if (request.getParameter("textsolution") != null) { File uploadedFile = new File(path, "textloesung.txt"); FileWriter fileWriter = new FileWriter(uploadedFile); fileWriter.write(request.getParameter("textsolution")); fileWriter.flush(); fileWriter.close(); submissionDAO.saveSubmission(submission); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } else { out.println("Problem: Keine Abgabedaten gefunden."); } } }
false
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Session session = HibernateSessionHelper.getSession(); Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session); Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0)); if (task == null) { template.printTemplateHeader("Aufgabe nicht gefunden"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } // check Lecture Participation ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session); Participation participation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture()); if (participation == null) { template.printTemplateHeader("Ung�ltige Anfrage"); out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>"); out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getStart().after(Util.correctTimezone(new Date())) && participation.getRoleType().compareTo(ParticipationRole.TUTOR) < 0) { template.printTemplateHeader("Aufgabe nicht abrufbar"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getDeadline().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) { template.printTemplateHeader("Abgabe nicht (mehr) m�glich"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session); Submission submission = submissionDAO.createSubmission(task, participation); ContextAdapter contextAdapter = new ContextAdapter(getServletContext()); File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator")); if (path.exists() == false) { path.mkdirs(); } //http://commons.apache.org/fileupload/using.html // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { if ("-".equals(task.getFilenameRegexp())) { request.setAttribute("title", "Dateiupload f�r diese Aufgabe deaktiviert."); request.getRequestDispatcher("MessageView").forward(request, response); return; } // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "filename invalid"); return; } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // Process a file upload if (!item.isFormField()) { Pattern pattern; if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty()) { pattern = Pattern.compile("(\\|/)?([a-zA-Z0-9_.-])$"); } else { System.out.println(task.getFilenameRegexp()); pattern = Pattern.compile("(\\|/)?(" + task.getFilenameRegexp() + ")$"); } System.out.println(pattern.pattern() + " " + item.getName()); Matcher m = pattern.matcher(item.getName()); if (!m.matches()) { out.println("Dateiname ung�ltig. Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt."); return; } String fileName = m.group(0); File uploadedFile = new File(path, fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } submissionDAO.saveSubmission(submission); new LogDAO(session).createLogEntry(LogAction.UPLOAD, null, null); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } } } else if (request.getParameter("textsolution") != null) { File uploadedFile = new File(path, "textloesung.txt"); FileWriter fileWriter = new FileWriter(uploadedFile); fileWriter.write(request.getParameter("textsolution")); fileWriter.flush(); fileWriter.close(); submissionDAO.saveSubmission(submission); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } else { out.println("Problem: Keine Abgabedaten gefunden."); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Session session = HibernateSessionHelper.getSession(); Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session); Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0)); if (task == null) { template.printTemplateHeader("Aufgabe nicht gefunden"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } // check Lecture Participation ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session); Participation participation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture()); if (participation == null) { template.printTemplateHeader("Ung�ltige Anfrage"); out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>"); out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getStart().after(Util.correctTimezone(new Date())) && participation.getRoleType().compareTo(ParticipationRole.TUTOR) < 0) { template.printTemplateHeader("Aufgabe nicht abrufbar"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } if (task.getDeadline().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) { template.printTemplateHeader("Abgabe nicht (mehr) m�glich"); out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>"); template.printTemplateFooter(); return; } SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session); Submission submission = submissionDAO.createSubmission(task, participation); ContextAdapter contextAdapter = new ContextAdapter(getServletContext()); File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator")); if (path.exists() == false) { path.mkdirs(); } //http://commons.apache.org/fileupload/using.html // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { if ("-".equals(task.getFilenameRegexp())) { request.setAttribute("title", "Dateiupload f�r diese Aufgabe deaktiviert."); request.getRequestDispatcher("MessageView").forward(request, response); return; } // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "filename invalid"); return; } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // Process a file upload if (!item.isFormField()) { Pattern pattern; if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty()) { pattern = Pattern.compile(".*?(?:\\\\|/)?([a-zA-Z0-9_.-]+)$"); } else { pattern = Pattern.compile(".*?(?:\\\\|/)?(" + task.getFilenameRegexp() + ")$"); } Matcher m = pattern.matcher(item.getName()); if (!m.matches()) { out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt."); return; } String fileName = m.group(1); File uploadedFile = new File(path, fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } submissionDAO.saveSubmission(submission); new LogDAO(session).createLogEntry(LogAction.UPLOAD, null, null); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } } } else if (request.getParameter("textsolution") != null) { File uploadedFile = new File(path, "textloesung.txt"); FileWriter fileWriter = new FileWriter(uploadedFile); fileWriter.write(request.getParameter("textsolution")); fileWriter.flush(); fileWriter.close(); submissionDAO.saveSubmission(submission); response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid())); } else { out.println("Problem: Keine Abgabedaten gefunden."); } }
diff --git a/src/com/programmingteam/main.java b/src/com/programmingteam/main.java index f98e5f6..0ed98a2 100644 --- a/src/com/programmingteam/main.java +++ b/src/com/programmingteam/main.java @@ -1,130 +1,130 @@ package com.programmingteam; import java.io.File; import java.util.ArrayList; import java.util.List; import com.programmingteam.qsync.QSync; import com.programmingteam.qsync.QSyncImport; import com.programmingteam.qsync.QSyncVcxproj; import com.programmingteam.vs2010.VcxprojSync; public class Main { public static Options OPTS; public static void main(String[] args) { OPTS = new Options(args); File qsyncFile = new File(OPTS.getFile()); if(!qsyncFile.exists()) { Log.e("Configuration file not found (" + OPTS.getFile() + ")"); System.exit(-1); } //Read file QSync qsync = new QSync(qsyncFile); qsync.debugPrint(); Log.v("Qsyn created ok."); List<QSyncVcxproj> qsyncProjs = qsync.getProjects(); for(QSyncVcxproj qsyncProj : qsyncProjs) { Log.d(">>> Sync: " + qsyncProj.getVcxproj() + ""); VcxprojSync vcxprojSync = new VcxprojSync(qsyncProj.getVcxproj(), qsyncProj.getVcxprojFilters()); for(QSyncImport imp: qsyncProj.getImportList()) { Log.d("Parsing <import tofilter=\"" + imp.getToFilter() + "\">"); vcxprojSync.invalidateFilters(imp.getToFilter()); ArrayList<File> dirList = new ArrayList<File>(); - dirList.add(new File(imp.getInclude())); - dirList.add(new File(imp.getSrc())); + if(imp.getInclude()!=null) dirList.add(new File(imp.getInclude())); + if(imp.getSrc()!=null) dirList.add(new File(imp.getSrc())); while(dirList.size()>0) { File dir = dirList.get(0); dirList.remove(0); File listFiles[] = dir.listFiles(); if(listFiles==null) { Log.e("Directory does not exist! " + dir); System.exit(-1); } for(int i=0; i<listFiles.length; ++i) { if(listFiles[i].isDirectory()) { dirList.add(listFiles[i]); if(imp.isIncludeEmptyDirs()) { String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFilter(toFilter); } } else { //TODO add handling misc boolean include =false; if( Helpers.isCompile(listFiles[i], qsync.getCompileExt()) || (include=Helpers.isInclude(listFiles[i], qsync.getIncludeExt()))) { if(include && !imp.matchesInclue(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } if(!include && !imp.matchesSrc(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } boolean isExcludedFromBuild = false; if(include) isExcludedFromBuild = imp.isExcludedInc(""+listFiles[i].getName()); else isExcludedFromBuild = imp.isExcludedSrc(""+listFiles[i].getName()); VcxprojSync.SyncType syncType = VcxprojSync.SyncType.COMPILE; if(include) syncType = VcxprojSync.SyncType.INCLUDE; String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.getPath(toFilter); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFile( qsyncProj.getRelativeFile(listFiles[i]), toFilter, syncType, isExcludedFromBuild); } } } } vcxprojSync.printLog(imp.getToFilter()); } //TODO save files! if(!OPTS.isPretend()) { vcxprojSync.saveVcxproj(OPTS.getOutput()); vcxprojSync.saveVcxprojFilters(OPTS.getOutput()); } else { Log.d("Pretend option: skipping file save..."); } Log.d("Done."); } } }
true
true
public static void main(String[] args) { OPTS = new Options(args); File qsyncFile = new File(OPTS.getFile()); if(!qsyncFile.exists()) { Log.e("Configuration file not found (" + OPTS.getFile() + ")"); System.exit(-1); } //Read file QSync qsync = new QSync(qsyncFile); qsync.debugPrint(); Log.v("Qsyn created ok."); List<QSyncVcxproj> qsyncProjs = qsync.getProjects(); for(QSyncVcxproj qsyncProj : qsyncProjs) { Log.d(">>> Sync: " + qsyncProj.getVcxproj() + ""); VcxprojSync vcxprojSync = new VcxprojSync(qsyncProj.getVcxproj(), qsyncProj.getVcxprojFilters()); for(QSyncImport imp: qsyncProj.getImportList()) { Log.d("Parsing <import tofilter=\"" + imp.getToFilter() + "\">"); vcxprojSync.invalidateFilters(imp.getToFilter()); ArrayList<File> dirList = new ArrayList<File>(); dirList.add(new File(imp.getInclude())); dirList.add(new File(imp.getSrc())); while(dirList.size()>0) { File dir = dirList.get(0); dirList.remove(0); File listFiles[] = dir.listFiles(); if(listFiles==null) { Log.e("Directory does not exist! " + dir); System.exit(-1); } for(int i=0; i<listFiles.length; ++i) { if(listFiles[i].isDirectory()) { dirList.add(listFiles[i]); if(imp.isIncludeEmptyDirs()) { String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFilter(toFilter); } } else { //TODO add handling misc boolean include =false; if( Helpers.isCompile(listFiles[i], qsync.getCompileExt()) || (include=Helpers.isInclude(listFiles[i], qsync.getIncludeExt()))) { if(include && !imp.matchesInclue(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } if(!include && !imp.matchesSrc(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } boolean isExcludedFromBuild = false; if(include) isExcludedFromBuild = imp.isExcludedInc(""+listFiles[i].getName()); else isExcludedFromBuild = imp.isExcludedSrc(""+listFiles[i].getName()); VcxprojSync.SyncType syncType = VcxprojSync.SyncType.COMPILE; if(include) syncType = VcxprojSync.SyncType.INCLUDE; String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.getPath(toFilter); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFile( qsyncProj.getRelativeFile(listFiles[i]), toFilter, syncType, isExcludedFromBuild); } } } } vcxprojSync.printLog(imp.getToFilter()); } //TODO save files! if(!OPTS.isPretend()) { vcxprojSync.saveVcxproj(OPTS.getOutput()); vcxprojSync.saveVcxprojFilters(OPTS.getOutput()); } else { Log.d("Pretend option: skipping file save..."); } Log.d("Done."); } }
public static void main(String[] args) { OPTS = new Options(args); File qsyncFile = new File(OPTS.getFile()); if(!qsyncFile.exists()) { Log.e("Configuration file not found (" + OPTS.getFile() + ")"); System.exit(-1); } //Read file QSync qsync = new QSync(qsyncFile); qsync.debugPrint(); Log.v("Qsyn created ok."); List<QSyncVcxproj> qsyncProjs = qsync.getProjects(); for(QSyncVcxproj qsyncProj : qsyncProjs) { Log.d(">>> Sync: " + qsyncProj.getVcxproj() + ""); VcxprojSync vcxprojSync = new VcxprojSync(qsyncProj.getVcxproj(), qsyncProj.getVcxprojFilters()); for(QSyncImport imp: qsyncProj.getImportList()) { Log.d("Parsing <import tofilter=\"" + imp.getToFilter() + "\">"); vcxprojSync.invalidateFilters(imp.getToFilter()); ArrayList<File> dirList = new ArrayList<File>(); if(imp.getInclude()!=null) dirList.add(new File(imp.getInclude())); if(imp.getSrc()!=null) dirList.add(new File(imp.getSrc())); while(dirList.size()>0) { File dir = dirList.get(0); dirList.remove(0); File listFiles[] = dir.listFiles(); if(listFiles==null) { Log.e("Directory does not exist! " + dir); System.exit(-1); } for(int i=0; i<listFiles.length; ++i) { if(listFiles[i].isDirectory()) { dirList.add(listFiles[i]); if(imp.isIncludeEmptyDirs()) { String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFilter(toFilter); } } else { //TODO add handling misc boolean include =false; if( Helpers.isCompile(listFiles[i], qsync.getCompileExt()) || (include=Helpers.isInclude(listFiles[i], qsync.getIncludeExt()))) { if(include && !imp.matchesInclue(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } if(!include && !imp.matchesSrc(listFiles[i].getName())) { Log.v("Skipping file: "+listFiles[i]+" (not matching regexp)"); continue; } boolean isExcludedFromBuild = false; if(include) isExcludedFromBuild = imp.isExcludedInc(""+listFiles[i].getName()); else isExcludedFromBuild = imp.isExcludedSrc(""+listFiles[i].getName()); VcxprojSync.SyncType syncType = VcxprojSync.SyncType.COMPILE; if(include) syncType = VcxprojSync.SyncType.INCLUDE; String toFilter = listFiles[i].getAbsolutePath() .replace(imp.getInclude(), imp.getToFilter()) .replace(imp.getSrc(), imp.getToFilter()); toFilter = Helpers.getPath(toFilter); toFilter = Helpers.stripSlashes(toFilter); vcxprojSync.syncFile( qsyncProj.getRelativeFile(listFiles[i]), toFilter, syncType, isExcludedFromBuild); } } } } vcxprojSync.printLog(imp.getToFilter()); } //TODO save files! if(!OPTS.isPretend()) { vcxprojSync.saveVcxproj(OPTS.getOutput()); vcxprojSync.saveVcxprojFilters(OPTS.getOutput()); } else { Log.d("Pretend option: skipping file save..."); } Log.d("Done."); } }
diff --git a/src/org/digitalcampus/oppia/widgets/PageWidget.java b/src/org/digitalcampus/oppia/widgets/PageWidget.java index 3a8f80b0..4cc72d66 100644 --- a/src/org/digitalcampus/oppia/widgets/PageWidget.java +++ b/src/org/digitalcampus/oppia/widgets/PageWidget.java @@ -1,222 +1,210 @@ /* * This file is part of OppiaMobile - http://oppia-mobile.org/ * * OppiaMobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OppiaMobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OppiaMobile. If not, see <http://www.gnu.org/licenses/>. */ package org.digitalcampus.oppia.widgets; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.digitalcampus.mobile.learning.R; import org.digitalcampus.oppia.activity.CourseActivity; import org.digitalcampus.oppia.application.DbHelper; import org.digitalcampus.oppia.application.MobileLearning; import org.digitalcampus.oppia.application.Tracker; import org.digitalcampus.oppia.model.Activity; import org.digitalcampus.oppia.model.Course; import org.digitalcampus.oppia.model.Media; import org.digitalcampus.oppia.utils.FileUtils; import org.digitalcampus.oppia.utils.MetaDataUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout.LayoutParams; import android.widget.Toast; public class PageWidget extends WidgetFactory { public static final String TAG = PageWidget.class.getSimpleName(); private Context ctx; private String mediaFileName; private WebView wv; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { prefs = PreferenceManager.getDefaultSharedPreferences(super.getActivity()); course = (Course) getArguments().getSerializable(Course.TAG); activity = (Activity) getArguments().getSerializable(Activity.TAG); this.setIsBaseline(getArguments().getBoolean(CourseActivity.BASELINE_TAG)); ctx = super.getActivity(); View vv = super.getLayoutInflater(savedInstanceState).inflate(R.layout.widget_page, null); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); vv.setLayoutParams(lp); return vv; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); wv = (WebView) ((android.app.Activity) ctx).findViewById(R.id.page_webview); // get the location data String url = course.getLocation() + activity.getLocation(prefs.getString(ctx.getString(R.string.prefs_language), Locale.getDefault().getLanguage())); - // find if there is specific stylesheet in course package - String styleLocation = "file:///android_asset/www/style.css"; - File styleSheet = new File(course.getLocation() + "/style.css"); - if(styleSheet.exists()){ - styleLocation = course.getLocation() + "/style.css"; - } try { - String content = "<html><head>"; - content += "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>"; - content += "<link href='" + styleLocation + "' rel='stylesheet' type='text/css'/>"; - content += "</head>"; - content += FileUtils.readFile(url); - content += "</html>"; - wv.loadDataWithBaseURL("file://" + course.getLocation() + "/", content, "text/html", "utf-8", null); + wv.loadDataWithBaseURL("file://" + course.getLocation() + "/", FileUtils.readFile(url), "text/html", "utf-8", null); } catch (IOException e) { e.printStackTrace(); wv.loadUrl("file://" + url); } // set up the page to intercept videos wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("/video/")) { Log.d(TAG, "Intercepting click on video url: " + url); // extract video name from url int startPos = url.indexOf("/video/") + 7; mediaFileName = url.substring(startPos, url.length()); // check video file exists boolean exists = FileUtils.mediaFileExists(mediaFileName); if (!exists) { Toast.makeText(ctx, ctx.getString(R.string.error_media_not_found,mediaFileName), Toast.LENGTH_LONG).show(); return true; } String mimeType = FileUtils.getMimeType(MobileLearning.MEDIA_PATH + mediaFileName); if(!FileUtils.supportedMediafileType(mimeType)){ Toast.makeText(ctx, ctx.getString(R.string.error_media_unsupported, mediaFileName), Toast.LENGTH_LONG).show(); return true; } // check user has app installed to play the video // launch intent to play video Intent intent = new Intent(android.content.Intent.ACTION_VIEW); Uri data = Uri.parse(MobileLearning.MEDIA_PATH + mediaFileName); intent.setDataAndType(data, "video/mp4"); PackageManager pm = PageWidget.this.ctx.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER); boolean appFound = false; for (ResolveInfo info : infos) { IntentFilter filter = info.filter; if (filter != null && filter.hasAction(Intent.ACTION_VIEW)) { // Found an app with the right intent/filter appFound = true; } } if (!appFound){ Toast.makeText(PageWidget.this.ctx, PageWidget.this.ctx.getString(R.string.error_media_app_not_found), Toast.LENGTH_LONG).show(); return true; } ctx.startActivity(intent); return true; } else { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse(url); intent.setData(data); ctx.startActivity(intent); // launch action in mobile browser - not the webview // return true so doesn't follow link within webview return true; } } }); } @Override public void onStop() { this.saveTracker(); super.onStop(); } @Override protected boolean getActivityCompleted() { // only show as being complete if all the videos on this page have been // played if (this.activity.hasMedia()) { ArrayList<Media> mediaList = this.activity.getMedia(); boolean completed = true; DbHelper db = new DbHelper(this.ctx); for (Media m : mediaList) { if (!db.activityCompleted(this.course.getModId(), m.getDigest())) { completed = false; } } db.close(); if (!completed) { return false; } } return true; } @Override protected void saveTracker(){ long timetaken = System.currentTimeMillis()/1000 - startTime; this.startTime = System.currentTimeMillis()/1000; // only save tracker if over the time if (timetaken < MobileLearning.PAGE_READ_TIME) { return; } Tracker t = new Tracker(ctx); JSONObject obj = new JSONObject(); MetaDataUtils mdu = new MetaDataUtils(ctx); // add in extra meta-data try { obj.put("timetaken", timetaken); obj = mdu.getMetaData(obj); String lang = prefs.getString(ctx.getString(R.string.prefs_language), Locale.getDefault().getLanguage()); obj.put("lang", lang); //obj.put("readaloud",readAloud); } catch (JSONException e) { // Do nothing } // if it's a baseline activity then assume completed if(this.isBaseline){ t.saveTracker(course.getModId(), activity.getDigest(), obj, true); } else { t.saveTracker(course.getModId(), activity.getDigest(), obj, this.getActivityCompleted()); } } }
false
true
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); wv = (WebView) ((android.app.Activity) ctx).findViewById(R.id.page_webview); // get the location data String url = course.getLocation() + activity.getLocation(prefs.getString(ctx.getString(R.string.prefs_language), Locale.getDefault().getLanguage())); // find if there is specific stylesheet in course package String styleLocation = "file:///android_asset/www/style.css"; File styleSheet = new File(course.getLocation() + "/style.css"); if(styleSheet.exists()){ styleLocation = course.getLocation() + "/style.css"; } try { String content = "<html><head>"; content += "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>"; content += "<link href='" + styleLocation + "' rel='stylesheet' type='text/css'/>"; content += "</head>"; content += FileUtils.readFile(url); content += "</html>"; wv.loadDataWithBaseURL("file://" + course.getLocation() + "/", content, "text/html", "utf-8", null); } catch (IOException e) { e.printStackTrace(); wv.loadUrl("file://" + url); } // set up the page to intercept videos wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("/video/")) { Log.d(TAG, "Intercepting click on video url: " + url); // extract video name from url int startPos = url.indexOf("/video/") + 7; mediaFileName = url.substring(startPos, url.length()); // check video file exists boolean exists = FileUtils.mediaFileExists(mediaFileName); if (!exists) { Toast.makeText(ctx, ctx.getString(R.string.error_media_not_found,mediaFileName), Toast.LENGTH_LONG).show(); return true; } String mimeType = FileUtils.getMimeType(MobileLearning.MEDIA_PATH + mediaFileName); if(!FileUtils.supportedMediafileType(mimeType)){ Toast.makeText(ctx, ctx.getString(R.string.error_media_unsupported, mediaFileName), Toast.LENGTH_LONG).show(); return true; } // check user has app installed to play the video // launch intent to play video Intent intent = new Intent(android.content.Intent.ACTION_VIEW); Uri data = Uri.parse(MobileLearning.MEDIA_PATH + mediaFileName); intent.setDataAndType(data, "video/mp4"); PackageManager pm = PageWidget.this.ctx.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER); boolean appFound = false; for (ResolveInfo info : infos) { IntentFilter filter = info.filter; if (filter != null && filter.hasAction(Intent.ACTION_VIEW)) { // Found an app with the right intent/filter appFound = true; } } if (!appFound){ Toast.makeText(PageWidget.this.ctx, PageWidget.this.ctx.getString(R.string.error_media_app_not_found), Toast.LENGTH_LONG).show(); return true; } ctx.startActivity(intent); return true; } else { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse(url); intent.setData(data); ctx.startActivity(intent); // launch action in mobile browser - not the webview // return true so doesn't follow link within webview return true; } } }); }
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); wv = (WebView) ((android.app.Activity) ctx).findViewById(R.id.page_webview); // get the location data String url = course.getLocation() + activity.getLocation(prefs.getString(ctx.getString(R.string.prefs_language), Locale.getDefault().getLanguage())); try { wv.loadDataWithBaseURL("file://" + course.getLocation() + "/", FileUtils.readFile(url), "text/html", "utf-8", null); } catch (IOException e) { e.printStackTrace(); wv.loadUrl("file://" + url); } // set up the page to intercept videos wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("/video/")) { Log.d(TAG, "Intercepting click on video url: " + url); // extract video name from url int startPos = url.indexOf("/video/") + 7; mediaFileName = url.substring(startPos, url.length()); // check video file exists boolean exists = FileUtils.mediaFileExists(mediaFileName); if (!exists) { Toast.makeText(ctx, ctx.getString(R.string.error_media_not_found,mediaFileName), Toast.LENGTH_LONG).show(); return true; } String mimeType = FileUtils.getMimeType(MobileLearning.MEDIA_PATH + mediaFileName); if(!FileUtils.supportedMediafileType(mimeType)){ Toast.makeText(ctx, ctx.getString(R.string.error_media_unsupported, mediaFileName), Toast.LENGTH_LONG).show(); return true; } // check user has app installed to play the video // launch intent to play video Intent intent = new Intent(android.content.Intent.ACTION_VIEW); Uri data = Uri.parse(MobileLearning.MEDIA_PATH + mediaFileName); intent.setDataAndType(data, "video/mp4"); PackageManager pm = PageWidget.this.ctx.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER); boolean appFound = false; for (ResolveInfo info : infos) { IntentFilter filter = info.filter; if (filter != null && filter.hasAction(Intent.ACTION_VIEW)) { // Found an app with the right intent/filter appFound = true; } } if (!appFound){ Toast.makeText(PageWidget.this.ctx, PageWidget.this.ctx.getString(R.string.error_media_app_not_found), Toast.LENGTH_LONG).show(); return true; } ctx.startActivity(intent); return true; } else { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse(url); intent.setData(data); ctx.startActivity(intent); // launch action in mobile browser - not the webview // return true so doesn't follow link within webview return true; } } }); }
diff --git a/src/main/java/opentree/TaxonomyContext.java b/src/main/java/opentree/TaxonomyContext.java index d532a77..3f5dbe4 100644 --- a/src/main/java/opentree/TaxonomyContext.java +++ b/src/main/java/opentree/TaxonomyContext.java @@ -1,127 +1,133 @@ package opentree; import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import opentree.ContextDescription; public class TaxonomyContext { private ContextDescription contextDescription; private Taxonomy taxonomy; TaxonomyContext(ContextDescription context, Taxonomy taxonomy) { this.contextDescription = context; this.taxonomy = taxonomy; } /** * Return a Neo4J index of the type defined by the passed NodeIndexDescription `index`, which is intended to be limited to the scope of the initiating taxonomic context * @param indexDesc * @return nodeIndex */ public Index<Node> getNodeIndex(NodeIndexDescription indexDesc) { String indexName = indexDesc.namePrefix + contextDescription.nameSuffix; return taxonomy.graphDb.getNodeIndex(indexName); } /** * Return the ContextDescription that underlies this TaxonomyContext object. * @return */ public ContextDescription getDescription() { return contextDescription; } /** * Return the root node for this taxonomic context * @return rootNode */ public Node getRootNode() { IndexHits<Node> rootMatches = taxonomy.ALLTAXA.getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_NAME).get("name", contextDescription.licaNodeName); Node rn = null; for (Node n : rootMatches) { - if (n.getProperty("taxcode").equals(contextDescription.nomenclature.code)) { + if (n.getProperty("name").equals(taxonomy.getLifeNode().getProperty("name"))) { + // if we find the life node, just return it rn = n; + break; + } else if (n.getProperty("taxcode").equals(contextDescription.nomenclature.code)) { + // otherwise check the taxcode to validate that this is the correct root, in case there are valid homonyms in other nomenclatures + rn = n; + break; } } rootMatches.close(); if (rn != null) { return rn; } else { throw new java.lang.IllegalStateException("Could not find the root node: " + contextDescription.licaNodeName + " in nomenclature + " + contextDescription.nomenclature.code); } } /** * a convenience wrapper for the taxNodes index .get("name", `name`) method * @param name * @return */ public List<Node> findTaxNodesByName(String name) { Index<Node> index = (Index<Node>) getNodeIndex(NodeIndexDescription.TAXON_BY_NAME); return findNodes(index, "name", name); } /** * a convenience wrapper for the prefTaxNodes index .get("name", `name`) method * @param name * @return */ public List<Node> findPrefTaxNodesByName(String name) { Index<Node> index = (Index<Node>) getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_NAME); return findNodes(index, "name", name); } /** * a generic wrapper for node indexes that searches the specified index for entries with `column` matching `key` * @param index * @param column * @param key * @return */ public List<Node> findNodes(Index<Node> index, String column, String key) { ArrayList<Node> foundNodes = new ArrayList<Node>(); IndexHits<Node> results = index.get(column, key); for (Node n : results) { foundNodes.add(n); } results.close(); return foundNodes; } /* IF THESE show common enough usage, it could be useful to provide them as well /** * a convenience wrapper for the prefSynNodes index .get("name", `name`) method * @param name * @return * public List<Node> findPrefTaxNodesBySyn(String name) { Index<Node> index = (Index<Node>) getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_SYNONYM); return findNodes(index, "name", name); } /** * a convenience wrapper for the prefTaxSynNodes index .get("name", `name`) method * @param name * @return * public List<Node> findPrefTaxNodesByNameOrSyn(String name) { Index<Node> index = (Index<Node>) getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_NAME_OR_SYNONYM); return findNodes(index, "name", name); } */ }
false
true
public Node getRootNode() { IndexHits<Node> rootMatches = taxonomy.ALLTAXA.getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_NAME).get("name", contextDescription.licaNodeName); Node rn = null; for (Node n : rootMatches) { if (n.getProperty("taxcode").equals(contextDescription.nomenclature.code)) { rn = n; } } rootMatches.close(); if (rn != null) { return rn; } else { throw new java.lang.IllegalStateException("Could not find the root node: " + contextDescription.licaNodeName + " in nomenclature + " + contextDescription.nomenclature.code); } }
public Node getRootNode() { IndexHits<Node> rootMatches = taxonomy.ALLTAXA.getNodeIndex(NodeIndexDescription.PREFERRED_TAXON_BY_NAME).get("name", contextDescription.licaNodeName); Node rn = null; for (Node n : rootMatches) { if (n.getProperty("name").equals(taxonomy.getLifeNode().getProperty("name"))) { // if we find the life node, just return it rn = n; break; } else if (n.getProperty("taxcode").equals(contextDescription.nomenclature.code)) { // otherwise check the taxcode to validate that this is the correct root, in case there are valid homonyms in other nomenclatures rn = n; break; } } rootMatches.close(); if (rn != null) { return rn; } else { throw new java.lang.IllegalStateException("Could not find the root node: " + contextDescription.licaNodeName + " in nomenclature + " + contextDescription.nomenclature.code); } }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/tests/TestsMake.java b/SWADroid/src/es/ugr/swad/swadroid/modules/tests/TestsMake.java index bc367fa5..8301b404 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/tests/TestsMake.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/tests/TestsMake.java @@ -1,725 +1,732 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.tests; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.ksoap2.SoapFault; import org.xmlpull.v1.XmlPullParserException; import android.database.Cursor; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.text.InputType; import android.util.Log; import android.util.SparseBooleanArray; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import es.ugr.swad.swadroid.Global; import es.ugr.swad.swadroid.Preferences; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.model.Test; import es.ugr.swad.swadroid.model.TestAnswer; import es.ugr.swad.swadroid.model.TestQuestion; import es.ugr.swad.swadroid.model.TestTag; import es.ugr.swad.swadroid.modules.Module; import es.ugr.swad.swadroid.widget.NumberPicker; import es.ugr.swad.swadroid.widget.TextProgressBar; /** * Tests module for evaluate user skills in a course * @author Juan Miguel Boyero Corral <[email protected]> * @author Helena Rodríguez Gijon <[email protected]> */ public class TestsMake extends Module { /** * Test's number of questions */ private int numQuestions; /** * Test data */ private Test test; /** * Tags's list of the test */ private List<TestTag> tagsList; /** * Answer types's list of the test */ private List<String> answerTypesList; /** * Click listener for courses dialog cancel button */ private OnItemClickListener tagsAnswersTypeItemClickListener; /** * Adapter for answer TF questions */ private ArrayAdapter<String> tfAdapter; /** * Test question being showed */ private int actualQuestion; /** * Tests tag name for Logcat */ public static final String TAG = Global.APP_TAG + " TestsMake"; /** * Application preferences. */ protected static Preferences prefs = new Preferences(); /** * Sets layout maintaining tests action bar * @param layout Layout to be applied */ private void setLayout(int layout) { ImageView image; TextView text; setContentView(layout); image = (ImageView)this.findViewById(R.id.moduleIcon); image.setBackgroundResource(R.drawable.test); text = (TextView)this.findViewById(R.id.moduleName); text.setText(R.string.testsModuleLabel); this.findViewById(R.id.courseSelectedText).setVisibility(View.VISIBLE); this.findViewById(R.id.groupSpinner).setVisibility(View.GONE); text = (TextView) this.findViewById(R.id.courseSelectedText); text.setText(Global.getSelectedCourseShortName()); } /** * Screen to select the number of questions in the test */ private void setNumQuestions() { final NumberPicker numberPicker; Button acceptButton; setLayout(R.layout.tests_num_questions); numberPicker = (NumberPicker)findViewById(R.id.testNumQuestionsNumberPicker); numberPicker.setRange(test.getMin(), test.getMax()); numberPicker.setCurrent(test.getDef()); acceptButton = (Button)findViewById(R.id.testNumQuestionsAcceptButton); acceptButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { numQuestions = numberPicker.getCurrent(); if(isDebuggable) { Log.d(TAG, "numQuestions="+numQuestions); } setTags(); } }); } /** * Screen to select the tags that will be present in the test */ private void setTags() { Button acceptButton; final ListView checkBoxesList; final TagsArrayAdapter tagsAdapter; final List<TestTag> allTagsList = dbHelper.getOrderedCourseTags(Global.getSelectedCourseCode()); //Add "All tags" item in list's top allTagsList.add(0, new TestTag(0, getResources().getString(R.string.allMsg), 0)); setLayout(R.layout.tests_tags); checkBoxesList = (ListView) findViewById(R.id.testTagsList); tagsAdapter = new TagsArrayAdapter(this, R.layout.list_item_multiple_choice, allTagsList); checkBoxesList.setAdapter(tagsAdapter); checkBoxesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); checkBoxesList.setOnItemClickListener(tagsAnswersTypeItemClickListener); acceptButton = (Button)findViewById(R.id.testTagsAcceptButton); acceptButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int childsCount = checkBoxesList.getCount(); SparseBooleanArray checkedItems = checkBoxesList.getCheckedItemPositions(); tagsList = new ArrayList<TestTag>(); //If "All tags" item checked, add the whole list to the list of selected tags if(checkedItems.get(0, false)) { tagsList.add(new TestTag(0, null, "all", 0)); //If "All tags" item is not checked, add the selected items to the list of selected tags } else { for(int i=0; i<childsCount; i++) { if(checkedItems.get(i, false)) { tagsList.add(tagsAdapter.getItem(i)); } } } if(isDebuggable) { Log.d(TAG, "tagsList="+tagsList.toString()); } //If no tags selected, show a message to notice user if(tagsList.isEmpty()) { Toast.makeText(getBaseContext(), R.string.testNoTagsSelectedMsg, Toast.LENGTH_LONG).show(); //If any tag is selected, show the answer types selection screen } else { setAnswerTypes(); } } }); } /** * Screen to select the answer types that will be present in the test */ private void setAnswerTypes() { Button acceptButton; final ListView checkBoxesList; final AnswerTypesArrayAdapter answerTypesAdapter; setLayout(R.layout.tests_answer_types); checkBoxesList = (ListView) findViewById(R.id.testAnswerTypesList); answerTypesAdapter = new AnswerTypesArrayAdapter(this, R.array.testAnswerTypes, R.array.testAnswerTypesNames, R.layout.list_item_multiple_choice); checkBoxesList.setAdapter(answerTypesAdapter); checkBoxesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); checkBoxesList.setOnItemClickListener(tagsAnswersTypeItemClickListener); acceptButton = (Button)findViewById(R.id.testAnswerTypesAcceptButton); acceptButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int childsCount = checkBoxesList.getCount(); SparseBooleanArray checkedItems = checkBoxesList.getCheckedItemPositions(); answerTypesList = new ArrayList<String>(); /* * If "All tags" item checked, add the whole list to the list of selected answer types, * else, add the selected items to the list of selected answer types */ if(checkedItems.get(0, false)) { answerTypesList.add("all"); } else { for(int i=1; i<childsCount; i++) { if(checkedItems.get(i, false)) { answerTypesList.add((String) answerTypesAdapter.getItem(i)); } } } if(isDebuggable) { Log.d(TAG, "answerTypesList="+answerTypesList.toString()); } //If no answer types selected, show a message to notice user if(answerTypesList.isEmpty()) { Toast.makeText(getBaseContext(), R.string.testNoAnswerTypesSelectedMsg, Toast.LENGTH_LONG) .show(); //If any answer type is selected, generate the test and show the first question screen } else { makeTest(); } } }); } /** * Shows a test question on screen * @param pos Question's position in questions's list of the test */ private void showQuestion(int pos) { TestQuestion question = test.getQuestions().get(pos); List<TestAnswer> answers = question.getAnswers(); TestAnswer a; ListView testMakeList = (ListView) findViewById(R.id.testMakeList); TextView stem = (TextView) findViewById(R.id.testMakeText); TextView score = (TextView) findViewById(R.id.testMakeQuestionScore); TextView textCorrectAnswer = (TextView) findViewById(R.id.testMakeCorrectAnswer); EditText textAnswer = (EditText) findViewById(R.id.testMakeEditText); ImageView img = (ImageView) findViewById(R.id.testMakeCorrectAnswerImage); CheckedAnswersArrayAdapter checkedAnswersAdapter; String answerType = question.getAnswerType(); String feedback = test.getFeedback(); String correctAnswer = ""; int numAnswers = answers.size(); Float questionScore; DecimalFormat df = new DecimalFormat("0.00"); score.setVisibility(View.GONE); textAnswer.setVisibility(View.GONE); textCorrectAnswer.setVisibility(View.GONE); testMakeList.setVisibility(View.GONE); img.setVisibility(View.GONE); stem.setText(Html.fromHtml(question.getStem())); if(answerType.equals("text") || answerType.equals("int") || answerType.equals("float")) { - if(!answerType.equals("text")) { - textAnswer.setRawInputType(InputType.TYPE_CLASS_NUMBER); + if(answerType.equals("int")) { + textAnswer.setInputType( + InputType.TYPE_CLASS_NUMBER + |InputType.TYPE_NUMBER_FLAG_SIGNED); + } else if(answerType.equals("float")) { + textAnswer.setInputType( + InputType.TYPE_CLASS_NUMBER + |InputType.TYPE_NUMBER_FLAG_DECIMAL + |InputType.TYPE_NUMBER_FLAG_SIGNED); } else { - textAnswer.setRawInputType(InputType.TYPE_CLASS_TEXT); + textAnswer.setInputType(InputType.TYPE_CLASS_TEXT); } a = answers.get(0); textAnswer.setText(a.getUserAnswer()); textAnswer.setVisibility(View.VISIBLE); if(test.isEvaluated() && feedback.equals("eachGoodBad")) { if(answerType.equals("float")) { correctAnswer = "[" + a.getAnswer() + ";" + answers.get(1).getAnswer() + "]"; } else { for(int i=0; i<numAnswers; i++) { a = answers.get(i); correctAnswer += a.getAnswer() + "<br/>"; } } textCorrectAnswer.setText(Html.fromHtml(correctAnswer)); textCorrectAnswer.setVisibility(View.VISIBLE); } } else if(answerType.equals("multipleChoice")) { checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_multiple_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); testMakeList.setItemChecked(i, Global.parseStringBool(a.getUserAnswer())); } testMakeList.setVisibility(View.VISIBLE); } else { if(answerType.equals("TF") && (numAnswers < 2)) { if(answers.get(0).getAnswer().equals("T")) { answers.add(1, new TestAnswer(0, 1, 0, false, "F")); } else { answers.add(0, new TestAnswer(0, 0, 0, false, "T")); } numAnswers = 2; } checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_single_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); if(a.getAnswer().equals(answers.get(0).getUserAnswer())) { testMakeList.setItemChecked(i, true); break; } } testMakeList.setVisibility(View.VISIBLE); } if(test.isEvaluated() && (feedback.equals("eachResult") || feedback.equals("eachGoodBad"))) { textAnswer.setEnabled(false); textAnswer.setOnClickListener(null); if(feedback.equals("eachGoodBad")) { img.setImageResource(R.drawable.btn_check_buttonless_on); if(!answerType.equals("TF") && !answerType.equals("multipleChoice") && !answerType.equals("uniqueChoice")) { if(!answers.get(0).isCorrectAnswered()) { img.setImageResource(android.R.drawable.ic_delete); } img.setVisibility(View.VISIBLE); } } questionScore = test.getQuestionScore(pos); if(questionScore > 0) { score.setTextColor(getResources().getColor(R.color.green)); } else if(questionScore < 0) { score.setTextColor(getResources().getColor(R.color.red)); } else { score.setTextColor(Color.BLACK); } score.setText(df.format(questionScore)); score.setVisibility(View.VISIBLE); } } /** * Reads the user answer of a question * @param q Question to read the answer */ private void readUserAnswer(TestQuestion q) { ListView testMakeList = (ListView) findViewById(R.id.testMakeList); EditText textAnswer = (EditText) findViewById(R.id.testMakeEditText); List<TestAnswer> la = q.getAnswers(); int checkedListCount, selectedPos; String answerType, userAnswer; SparseBooleanArray checkedItems; answerType = q.getAnswerType(); if(answerType.equals("text") || answerType.equals("int") || answerType.equals("float")) { la.get(0).setUserAnswer(String.valueOf(textAnswer.getText())); } else if(answerType.equals("multipleChoice")) { checkedItems = testMakeList.getCheckedItemPositions(); checkedListCount = checkedItems.size(); for(int i=0; i<checkedListCount; i++) { la.get(i).setUserAnswer(Global.parseBoolString(checkedItems.get(i, false))); } } else { selectedPos = testMakeList.getCheckedItemPosition(); if(selectedPos == -1) { userAnswer = ""; } else { userAnswer = la.get(selectedPos).getAnswer(); } la.get(0).setUserAnswer(userAnswer); } } /** * Shows the test */ private void showTest() { final TextProgressBar bar; Button prev, next, eval; final int size = test.getQuestions().size(); setLayout(R.layout.tests_make_questions); prev = (Button) findViewById(R.id.testMakePrevButton); next = (Button) findViewById(R.id.testMakeNextButton); eval = (Button) findViewById(R.id.testEvaluateButton); //title_separator = (ImageView) findViewById(R.id.title_sep_2); bar = (TextProgressBar) findViewById(R.id.test_questions_bar); bar.setMax(size); bar.setProgress(1); bar.setText(1 + "/" + size); bar.setTextColor(Color.BLUE); bar.setTextSize(20); eval.setVisibility(View.VISIBLE); //title_separator.setVisibility(View.VISIBLE); actualQuestion = 0; prev.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TestQuestion question = test.getQuestionAndAnswers(actualQuestion); int pos; if(!test.isEvaluated()) { readUserAnswer(question); } actualQuestion--; if(actualQuestion < 0) { actualQuestion = size-1; } pos = actualQuestion+1; showQuestion(actualQuestion); bar.setProgress(pos); bar.setText(pos + "/" + size); } }); next.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TestQuestion question = test.getQuestionAndAnswers(actualQuestion); int pos; if(!test.isEvaluated()) { readUserAnswer(question); } actualQuestion++; actualQuestion %= size; pos = actualQuestion+1; showQuestion(actualQuestion); bar.setProgress(pos); bar.setText(pos + "/" + size); } }); showQuestion(0); } /** * Generates the test */ private void makeTest() { List<TestQuestion> questions; //Generates the test questions = dbHelper.getRandomCourseQuestionsByTagAndAnswerType(Global.getSelectedCourseCode(), tagsList, answerTypesList, numQuestions); if(!questions.isEmpty()) { test.setQuestions(questions); //Shuffles related answers in a question if necessary for(TestQuestion q : questions) { if(q.getShuffle()) { q.shuffleAnswers(); } } //Shows the test showTest(); } else { Toast.makeText(this, R.string.testNoQuestionsMeetsSpecifiedCriteriaMsg, Toast.LENGTH_LONG).show(); finish(); } } /** * Launches an action when evaluate button is pushed * @param v Actual view */ public void onEvaluateClick(View v) { TextView textView; Button bt, evalBt; Float score, scoreDec; DecimalFormat df = new DecimalFormat("0.00"); String feedback = test.getFeedback(); readUserAnswer(test.getQuestionAndAnswers(actualQuestion)); setLayout(R.layout.tests_make_results); if(!feedback.equals("nothing")) { if(!test.isEvaluated()) { test.evaluate(); evalBt = (Button) findViewById(R.id.testEvaluateButton); //sep2 = (ImageView) findViewById(R.id.title_sep_2); evalBt.setVisibility(View.GONE); //sep2.setVisibility(View.GONE); } score = test.getTotalScore(); scoreDec = (score/test.getQuestions().size())*10; textView = (TextView) findViewById(R.id.testResultsScore); textView.setText(df.format(score) + "/" + test.getQuestions().size() + "\n" + df.format(scoreDec) + "/10"); if(scoreDec < 5) { textView.setTextColor(getResources().getColor(R.color.red)); } bt = (Button) findViewById(R.id.testResultsButton); if(feedback.equals("totalResult")) { bt.setEnabled(false); bt.setText(R.string.testNoDetailsMsg); } textView.setVisibility(View.VISIBLE); bt.setVisibility(View.VISIBLE); } else { textView = (TextView) findViewById(R.id.testResultsText); textView.setText(R.string.testNoResultsMsg); } } /** * Launches an action when show results details button is pushed * @param v Actual view */ public void onShowResultsDetailsClick(View v) { Button evalBt, resBt; //ImageView sep2, sep3; showTest(); evalBt = (Button) findViewById(R.id.testEvaluateButton); //sep2 = (ImageView) findViewById(R.id.title_sep_2); resBt = (Button) findViewById(R.id.testShowResultsButton); //sep3 = (ImageView) findViewById(R.id.title_sep_3); evalBt.setVisibility(View.GONE); //sep2.setVisibility(View.GONE); resBt.setVisibility(View.VISIBLE); //sep3.setVisibility(View.VISIBLE); } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setLayout(R.layout.layout_with_action_bar); tagsAnswersTypeItemClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //CheckedTextView chk = (CheckedTextView) v; ListView lv = (ListView) parent; int childCount = lv.getCount(); SparseBooleanArray checkedItems = lv.getCheckedItemPositions(); boolean allChecked = true; if(position == 0) { for(int i=1; i<childCount; i++) { lv.setItemChecked(i, checkedItems.get(0, false)); } } else { for(int i=1; i<childCount; i++) { if(!checkedItems.get(i, false)) { allChecked = false; } } if (allChecked) { lv.setItemChecked(0, true); } else { lv.setItemChecked(0, false); } } } }; tfAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); tfAdapter.add(getString(R.string.trueMsg)); tfAdapter.add(getString(R.string.falseMsg)); prefs.getPreferences(getBaseContext()); String selection ="id=" + Long.toString(Global.getSelectedCourseCode()); Cursor dbCursor = dbHelper.getDb().getCursor(Global.DB_TABLE_TEST_CONFIG,selection,null); startManagingCursor(dbCursor); if(dbCursor.getCount() > 0) { if(isDebuggable) { Log.d(TAG, "selectedCourseCode = " + Long.toString(Global.getSelectedCourseCode())); } test = (Test) dbHelper.getRow(Global.DB_TABLE_TEST_CONFIG, "id", Long.toString(Global.getSelectedCourseCode())); if(test != null) { setNumQuestions(); } else { Toast.makeText(getBaseContext(), R.string.testNoQuestionsCourseMsg, Toast.LENGTH_LONG).show(); finish(); } } else { Toast.makeText(getBaseContext(), R.string.testNoQuestionsMsg, Toast.LENGTH_LONG).show(); finish(); } setResult(RESULT_OK); } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onStart() */ /*@Override protected void onStart() { super.onStart(); prefs.getPreferences(getBaseContext()); String selection ="id=" + Long.toString(Global.getSelectedCourseCode()); Cursor dbCursor = dbHelper.getDb().getCursor(Global.DB_TABLE_TEST_CONFIG,selection,null); startManagingCursor(dbCursor); if(dbCursor.getCount() > 0) { if(isDebuggable) { Log.d(TAG, "selectedCourseCode = " + Long.toString(Global.getSelectedCourseCode())); } test = (Test) dbHelper.getRow(Global.DB_TABLE_TEST_CONFIG, "id", Long.toString(Global.getSelectedCourseCode())); if(test != null) { setNumQuestions(); } else { Toast.makeText(getBaseContext(), R.string.testNoQuestionsCourseMsg, Toast.LENGTH_LONG).show(); finish(); } } else { Toast.makeText(getBaseContext(), R.string.testNoQuestionsMsg, Toast.LENGTH_LONG).show(); finish(); } }*/ /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#requestService() */ @Override protected void requestService() throws NoSuchAlgorithmException, IOException, XmlPullParserException, SoapFault, IllegalAccessException, InstantiationException { } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#connect() */ @Override protected void connect() { } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#postConnect() */ @Override protected void postConnect() { } /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onError() */ @Override protected void onError() { } }
false
true
private void showQuestion(int pos) { TestQuestion question = test.getQuestions().get(pos); List<TestAnswer> answers = question.getAnswers(); TestAnswer a; ListView testMakeList = (ListView) findViewById(R.id.testMakeList); TextView stem = (TextView) findViewById(R.id.testMakeText); TextView score = (TextView) findViewById(R.id.testMakeQuestionScore); TextView textCorrectAnswer = (TextView) findViewById(R.id.testMakeCorrectAnswer); EditText textAnswer = (EditText) findViewById(R.id.testMakeEditText); ImageView img = (ImageView) findViewById(R.id.testMakeCorrectAnswerImage); CheckedAnswersArrayAdapter checkedAnswersAdapter; String answerType = question.getAnswerType(); String feedback = test.getFeedback(); String correctAnswer = ""; int numAnswers = answers.size(); Float questionScore; DecimalFormat df = new DecimalFormat("0.00"); score.setVisibility(View.GONE); textAnswer.setVisibility(View.GONE); textCorrectAnswer.setVisibility(View.GONE); testMakeList.setVisibility(View.GONE); img.setVisibility(View.GONE); stem.setText(Html.fromHtml(question.getStem())); if(answerType.equals("text") || answerType.equals("int") || answerType.equals("float")) { if(!answerType.equals("text")) { textAnswer.setRawInputType(InputType.TYPE_CLASS_NUMBER); } else { textAnswer.setRawInputType(InputType.TYPE_CLASS_TEXT); } a = answers.get(0); textAnswer.setText(a.getUserAnswer()); textAnswer.setVisibility(View.VISIBLE); if(test.isEvaluated() && feedback.equals("eachGoodBad")) { if(answerType.equals("float")) { correctAnswer = "[" + a.getAnswer() + ";" + answers.get(1).getAnswer() + "]"; } else { for(int i=0; i<numAnswers; i++) { a = answers.get(i); correctAnswer += a.getAnswer() + "<br/>"; } } textCorrectAnswer.setText(Html.fromHtml(correctAnswer)); textCorrectAnswer.setVisibility(View.VISIBLE); } } else if(answerType.equals("multipleChoice")) { checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_multiple_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); testMakeList.setItemChecked(i, Global.parseStringBool(a.getUserAnswer())); } testMakeList.setVisibility(View.VISIBLE); } else { if(answerType.equals("TF") && (numAnswers < 2)) { if(answers.get(0).getAnswer().equals("T")) { answers.add(1, new TestAnswer(0, 1, 0, false, "F")); } else { answers.add(0, new TestAnswer(0, 0, 0, false, "T")); } numAnswers = 2; } checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_single_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); if(a.getAnswer().equals(answers.get(0).getUserAnswer())) { testMakeList.setItemChecked(i, true); break; } } testMakeList.setVisibility(View.VISIBLE); } if(test.isEvaluated() && (feedback.equals("eachResult") || feedback.equals("eachGoodBad"))) { textAnswer.setEnabled(false); textAnswer.setOnClickListener(null); if(feedback.equals("eachGoodBad")) { img.setImageResource(R.drawable.btn_check_buttonless_on); if(!answerType.equals("TF") && !answerType.equals("multipleChoice") && !answerType.equals("uniqueChoice")) { if(!answers.get(0).isCorrectAnswered()) { img.setImageResource(android.R.drawable.ic_delete); } img.setVisibility(View.VISIBLE); } } questionScore = test.getQuestionScore(pos); if(questionScore > 0) { score.setTextColor(getResources().getColor(R.color.green)); } else if(questionScore < 0) { score.setTextColor(getResources().getColor(R.color.red)); } else { score.setTextColor(Color.BLACK); } score.setText(df.format(questionScore)); score.setVisibility(View.VISIBLE); } }
private void showQuestion(int pos) { TestQuestion question = test.getQuestions().get(pos); List<TestAnswer> answers = question.getAnswers(); TestAnswer a; ListView testMakeList = (ListView) findViewById(R.id.testMakeList); TextView stem = (TextView) findViewById(R.id.testMakeText); TextView score = (TextView) findViewById(R.id.testMakeQuestionScore); TextView textCorrectAnswer = (TextView) findViewById(R.id.testMakeCorrectAnswer); EditText textAnswer = (EditText) findViewById(R.id.testMakeEditText); ImageView img = (ImageView) findViewById(R.id.testMakeCorrectAnswerImage); CheckedAnswersArrayAdapter checkedAnswersAdapter; String answerType = question.getAnswerType(); String feedback = test.getFeedback(); String correctAnswer = ""; int numAnswers = answers.size(); Float questionScore; DecimalFormat df = new DecimalFormat("0.00"); score.setVisibility(View.GONE); textAnswer.setVisibility(View.GONE); textCorrectAnswer.setVisibility(View.GONE); testMakeList.setVisibility(View.GONE); img.setVisibility(View.GONE); stem.setText(Html.fromHtml(question.getStem())); if(answerType.equals("text") || answerType.equals("int") || answerType.equals("float")) { if(answerType.equals("int")) { textAnswer.setInputType( InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_SIGNED); } else if(answerType.equals("float")) { textAnswer.setInputType( InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_DECIMAL |InputType.TYPE_NUMBER_FLAG_SIGNED); } else { textAnswer.setInputType(InputType.TYPE_CLASS_TEXT); } a = answers.get(0); textAnswer.setText(a.getUserAnswer()); textAnswer.setVisibility(View.VISIBLE); if(test.isEvaluated() && feedback.equals("eachGoodBad")) { if(answerType.equals("float")) { correctAnswer = "[" + a.getAnswer() + ";" + answers.get(1).getAnswer() + "]"; } else { for(int i=0; i<numAnswers; i++) { a = answers.get(i); correctAnswer += a.getAnswer() + "<br/>"; } } textCorrectAnswer.setText(Html.fromHtml(correctAnswer)); textCorrectAnswer.setVisibility(View.VISIBLE); } } else if(answerType.equals("multipleChoice")) { checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_multiple_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); testMakeList.setItemChecked(i, Global.parseStringBool(a.getUserAnswer())); } testMakeList.setVisibility(View.VISIBLE); } else { if(answerType.equals("TF") && (numAnswers < 2)) { if(answers.get(0).getAnswer().equals("T")) { answers.add(1, new TestAnswer(0, 1, 0, false, "F")); } else { answers.add(0, new TestAnswer(0, 0, 0, false, "T")); } numAnswers = 2; } checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_single_choice, answers, test.isEvaluated(), test.getFeedback(), answerType); testMakeList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); testMakeList.setAdapter(checkedAnswersAdapter); for(int i=0; i<numAnswers; i++) { a = answers.get(i); if(a.getAnswer().equals(answers.get(0).getUserAnswer())) { testMakeList.setItemChecked(i, true); break; } } testMakeList.setVisibility(View.VISIBLE); } if(test.isEvaluated() && (feedback.equals("eachResult") || feedback.equals("eachGoodBad"))) { textAnswer.setEnabled(false); textAnswer.setOnClickListener(null); if(feedback.equals("eachGoodBad")) { img.setImageResource(R.drawable.btn_check_buttonless_on); if(!answerType.equals("TF") && !answerType.equals("multipleChoice") && !answerType.equals("uniqueChoice")) { if(!answers.get(0).isCorrectAnswered()) { img.setImageResource(android.R.drawable.ic_delete); } img.setVisibility(View.VISIBLE); } } questionScore = test.getQuestionScore(pos); if(questionScore > 0) { score.setTextColor(getResources().getColor(R.color.green)); } else if(questionScore < 0) { score.setTextColor(getResources().getColor(R.color.red)); } else { score.setTextColor(Color.BLACK); } score.setText(df.format(questionScore)); score.setVisibility(View.VISIBLE); } }
diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java index 3c5d9b88..cb29af08 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java @@ -1,215 +1,215 @@ package com.earth2me.essentials.antibuild; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.User; import java.util.logging.Level; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; public class EssentialsAntiBuildListener implements Listener { final private transient IAntiBuild prot; final private transient IEssentials ess; public EssentialsAntiBuildListener(final IAntiBuild parent) { this.prot = parent; this.ess = prot.getEssentialsConnect().getEssentials(); } private boolean metaPermCheck(User user, String action, Block block) { if (block == null) { return false; } return metaPermCheck(user, action, block.getTypeId(), block.getData()); } private boolean metaPermCheck(User user, String action, int blockId, byte data) { final String blockPerm = "essentials.build." + action + "." + blockId; final String dataPerm = blockPerm + ":" + data; if (user.isPermissionSet(dataPerm)) { return user.isAuthorized(dataPerm); } else { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "abort checking if " + user.getName() + " has " + dataPerm + " - not directly set"); } } return user.isAuthorized(blockPerm); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPlace(final BlockPlaceEvent event) { if (event.isCancelled()) { return; } final User user = ess.getUser(event.getPlayer()); if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "place", event.getBlock())) { if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } event.setCancelled(true); return; } final Block blockPlaced = event.getBlockPlaced(); final int id = blockPlaced.getTypeId(); if (prot.checkProtectionItems(AntiBuildConfig.blacklist_placement, id) && !user.isAuthorized("essentials.protect.exemptplacement")) { event.setCancelled(true); return; } if (prot.checkProtectionItems(AntiBuildConfig.alert_on_placement, id) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { prot.getEssentialsConnect().alert(user, blockPlaced.getType().toString(), _("alertPlaced")); } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(final BlockBreakEvent event) { if (event.isCancelled()) { return; } final User user = ess.getUser(event.getPlayer()); if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "break", event.getBlock())) { if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } event.setCancelled(true); return; } final Block block = event.getBlock(); final int typeId = block.getTypeId(); if (prot.checkProtectionItems(AntiBuildConfig.blacklist_break, typeId) && !user.isAuthorized("essentials.protect.exemptbreak")) { event.setCancelled(true); return; } final Material type = block.getType(); if (prot.checkProtectionItems(AntiBuildConfig.alert_on_break, typeId) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { prot.getEssentialsConnect().alert(user, type.toString(), _("alertBroke")); } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonExtend(BlockPistonExtendEvent event) { if (event.isCancelled()) { return; } for (Block block : event.getBlocks()) { if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) { event.setCancelled(true); return; } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonRetract(BlockPistonRetractEvent event) { if (event.isCancelled() || !event.isSticky()) { return; } final Block block = event.getRetractLocation().getBlock(); if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) { event.setCancelled(true); return; } } @EventHandler(priority = EventPriority.LOW) public void onPlayerInteract(final PlayerInteractEvent event) { // Do not return if cancelled, because the interact event has 2 cancelled states. final User user = ess.getUser(event.getPlayer()); if (event.hasItem() && (event.getItem().getType() == Material.WATER_BUCKET || event.getItem().getType() == Material.LAVA_BUCKET) && prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) { if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } event.setCancelled(true); return; } final ItemStack item = event.getItem(); if (item != null && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) { event.setCancelled(true); return; } if (item != null && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getTypeId()) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); } - if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.interact") && !user.isAuthorized("essentials.build")) + if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { if (!metaPermCheck(user, "interact", event.getClickedBlock())) { event.setUseInteractedBlock(Result.DENY); if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } } if (event.hasItem() && !metaPermCheck(user, "use", event.getItem().getTypeId(), event.getItem().getData().getData())) { event.setUseItemInHand(Result.DENY); } } } }
true
true
public void onPlayerInteract(final PlayerInteractEvent event) { // Do not return if cancelled, because the interact event has 2 cancelled states. final User user = ess.getUser(event.getPlayer()); if (event.hasItem() && (event.getItem().getType() == Material.WATER_BUCKET || event.getItem().getType() == Material.LAVA_BUCKET) && prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) { if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } event.setCancelled(true); return; } final ItemStack item = event.getItem(); if (item != null && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) { event.setCancelled(true); return; } if (item != null && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getTypeId()) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); } if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.interact") && !user.isAuthorized("essentials.build")) { if (!metaPermCheck(user, "interact", event.getClickedBlock())) { event.setUseInteractedBlock(Result.DENY); if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } } if (event.hasItem() && !metaPermCheck(user, "use", event.getItem().getTypeId(), event.getItem().getData().getData())) { event.setUseItemInHand(Result.DENY); } } }
public void onPlayerInteract(final PlayerInteractEvent event) { // Do not return if cancelled, because the interact event has 2 cancelled states. final User user = ess.getUser(event.getPlayer()); if (event.hasItem() && (event.getItem().getType() == Material.WATER_BUCKET || event.getItem().getType() == Material.LAVA_BUCKET) && prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) { if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } event.setCancelled(true); return; } final ItemStack item = event.getItem(); if (item != null && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) { event.setCancelled(true); return; } if (item != null && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getTypeId()) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); } if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { if (!metaPermCheck(user, "interact", event.getClickedBlock())) { event.setUseInteractedBlock(Result.DENY); if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(_("buildAlert")); } } if (event.hasItem() && !metaPermCheck(user, "use", event.getItem().getTypeId(), event.getItem().getData().getData())) { event.setUseItemInHand(Result.DENY); } } }
diff --git a/src/org/tomahawk/libtomahawk/audio/PlaybackService.java b/src/org/tomahawk/libtomahawk/audio/PlaybackService.java index ecf361de..3592062d 100644 --- a/src/org/tomahawk/libtomahawk/audio/PlaybackService.java +++ b/src/org/tomahawk/libtomahawk/audio/PlaybackService.java @@ -1,640 +1,642 @@ /* == This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2012, Christopher Reichert <[email protected]> * * Tomahawk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tomahawk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ package org.tomahawk.libtomahawk.audio; import java.io.IOException; import org.tomahawk.libtomahawk.Track; import org.tomahawk.libtomahawk.playlist.Playlist; import org.tomahawk.tomahawk_android.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.*; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.os.*; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.RemoteViews; public class PlaybackService extends Service implements OnCompletionListener, OnErrorListener, OnPreparedListener { private static String TAG = PlaybackService.class.getName(); private final IBinder mBinder = new PlaybackServiceBinder(); public static final String BROADCAST_NEWTRACK = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_NEWTRACK"; public static final String BROADCAST_PLAYLISTCHANGED = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_PLAYLISTCHANGED"; public static final String BROADCAST_PLAYSTATECHANGED = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_PLAYSTATECHANGED"; public static final String BROADCAST_NOTIFICATIONINTENT_PREVIOUS = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_NOTIFICATIONINTENT_PREVIOUS"; public static final String BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE"; public static final String BROADCAST_NOTIFICATIONINTENT_NEXT = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_NOTIFICATIONINTENT_NEXT"; public static final String BROADCAST_NOTIFICATIONINTENT_EXIT = "org.tomahawk.libtomahawk.audio.PlaybackService.BROADCAST_NOTIFICATIONINTENT_EXIT"; private static final int PLAYBACKSERVICE_PLAYSTATE_PLAYING = 0; private static final int PLAYBACKSERVICE_PLAYSTATE_PAUSED = 1; private static final int PLAYBACKSERVICE_PLAYSTATE_STOPPED = 2; private int mPlayState = PLAYBACKSERVICE_PLAYSTATE_PLAYING; private static final int PLAYBACKSERVICE_NOTIFICATION_ID = 0; private static final int DELAY_TO_KILL = 100000; private Playlist mCurrentPlaylist; private MediaPlayer mMediaPlayer; private PowerManager.WakeLock mWakeLock; private boolean mIsPreparing; private ServiceBroadcastReceiver mServiceBroadcastReceiver; private Handler mHandler; public static class PlaybackServiceConnection implements ServiceConnection { private PlaybackServiceConnectionListener mPlaybackServiceConnectionListener; public interface PlaybackServiceConnectionListener { public void setPlaybackService(PlaybackService ps); public void onPlaybackServiceReady(); } public PlaybackServiceConnection(PlaybackServiceConnectionListener playbackServiceConnectedListener) { mPlaybackServiceConnectionListener = playbackServiceConnectedListener; } @Override public void onServiceConnected(ComponentName className, IBinder service) { PlaybackServiceBinder binder = (PlaybackServiceBinder) service; mPlaybackServiceConnectionListener.setPlaybackService(binder.getService()); mPlaybackServiceConnectionListener.onPlaybackServiceReady(); } @Override public void onServiceDisconnected(ComponentName arg0) { mPlaybackServiceConnectionListener.setPlaybackService(null); } }; /** * Listens for incoming phone calls and handles playback. */ private class PhoneCallListener extends PhoneStateListener { private long mStartCallTime = 0L; /* (non-Javadoc) * @see android.telephony.PhoneStateListener#onCallStateChanged(int, java.lang.String) */ @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_RINGING: case TelephonyManager.CALL_STATE_OFFHOOK: if (isPlaying()) { mStartCallTime = System.currentTimeMillis(); pause(); } break; case TelephonyManager.CALL_STATE_IDLE: if (mStartCallTime > 0 && (System.currentTimeMillis() - mStartCallTime < 30000)) { mVolumeIncreaseFader.run(); start(); } mStartCallTime = 0L; break; } } } private class ServiceBroadcastReceiver extends BroadcastReceiver { private boolean headsetConnected; @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra("state")) { if (headsetConnected && intent.getIntExtra("state", 0) == 0) { headsetConnected = false; if (isPlaying()) { pause(); } } else if (!headsetConnected && intent.getIntExtra("state", 0) == 1) { headsetConnected = true; } } else if (intent.getAction() == BROADCAST_NOTIFICATIONINTENT_PREVIOUS) { previous(); } else if (intent.getAction() == BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE) { playPause(); } else if (intent.getAction() == BROADCAST_NOTIFICATIONINTENT_NEXT) { next(); } else if (intent.getAction() == BROADCAST_NOTIFICATIONINTENT_EXIT) { pause(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYBACKSERVICE_NOTIFICATION_ID); } } } public class PlaybackServiceBinder extends Binder { public PlaybackService getService() { return PlaybackService.this; } } /** * This Runnable is used to increase the volume gently. */ private Runnable mVolumeIncreaseFader = new Runnable() { private float mVolume = 0f; @Override public void run() { mMediaPlayer.setVolume(mVolume, mVolume); if (mVolume < 1.0f) { mVolume += .05f; mHandler.postDelayed(mVolumeIncreaseFader, 250); } else mVolume = 0; } }; /* (non-Javadoc) * @see android.app.Service#onCreate() */ @Override public void onCreate() { mHandler = new Handler(); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(new PhoneCallListener(), PhoneStateListener.LISTEN_CALL_STATE); initMediaPlayer(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mServiceBroadcastReceiver = new ServiceBroadcastReceiver(); registerReceiver(mServiceBroadcastReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG)); registerReceiver(mServiceBroadcastReceiver, new IntentFilter(BROADCAST_NOTIFICATIONINTENT_PREVIOUS)); registerReceiver(mServiceBroadcastReceiver, new IntentFilter(BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE)); registerReceiver(mServiceBroadcastReceiver, new IntentFilter(BROADCAST_NOTIFICATIONINTENT_NEXT)); registerReceiver(mServiceBroadcastReceiver, new IntentFilter(BROADCAST_NOTIFICATIONINTENT_EXIT)); } @Override public int onStartCommand(Intent intent, int flags, int startId) { mKillTimerHandler.removeCallbacksAndMessages(null); Message msg = mKillTimerHandler.obtainMessage(); mKillTimerHandler.sendMessageDelayed(msg, DELAY_TO_KILL); return START_STICKY; } @Override public boolean onUnbind(Intent intent) { if (isPlaying()) { Message msg = mKillTimerHandler.obtainMessage(); mKillTimerHandler.sendMessageDelayed(msg, DELAY_TO_KILL); return true; } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYBACKSERVICE_NOTIFICATION_ID); stopSelf(); return true; } private final Handler mKillTimerHandler = new Handler() { @Override public void handleMessage(Message msg) { if (isPlaying()) { return; } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYBACKSERVICE_NOTIFICATION_ID); stopSelf(); } }; /** * Initializes the mediaplayer. Sets the listeners and AudioStreamType. */ public void initMediaPlayer() { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnErrorListener(this); } /* (non-Javadoc) * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { unregisterReceiver(mServiceBroadcastReceiver); mMediaPlayer.release(); if (mWakeLock.isHeld()) mWakeLock.release(); } /* (non-Javadoc) * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } public void handlePlayState() { if (!mIsPreparing) { switch (mPlayState) { case PLAYBACKSERVICE_PLAYSTATE_PLAYING: if (!mWakeLock.isHeld()) mWakeLock.acquire(); mMediaPlayer.start(); updatePlayingNotification(); break; case PLAYBACKSERVICE_PLAYSTATE_PAUSED: if (mMediaPlayer.isPlaying()) mMediaPlayer.pause(); if (mWakeLock.isHeld()) mWakeLock.release(); updatePlayingNotification(); break; case PLAYBACKSERVICE_PLAYSTATE_STOPPED: mMediaPlayer.stop(); if (mWakeLock.isHeld()) mWakeLock.release(); updatePlayingNotification(); } } } /** * Start or pause playback. */ public void playPause() { if (mPlayState == PLAYBACKSERVICE_PLAYSTATE_PLAYING) mPlayState = PLAYBACKSERVICE_PLAYSTATE_PAUSED; else if (mPlayState == PLAYBACKSERVICE_PLAYSTATE_PAUSED || mPlayState == PLAYBACKSERVICE_PLAYSTATE_STOPPED) mPlayState = PLAYBACKSERVICE_PLAYSTATE_PLAYING; sendBroadcast(new Intent(BROADCAST_PLAYSTATECHANGED)); handlePlayState(); } /** * Initial start of playback. Acquires wakelock and creates a notification * */ public void start() { mPlayState = PLAYBACKSERVICE_PLAYSTATE_PLAYING; sendBroadcast(new Intent(BROADCAST_PLAYSTATECHANGED)); handlePlayState(); } /** * Stop playback. */ public void stop() { mPlayState = PLAYBACKSERVICE_PLAYSTATE_STOPPED; sendBroadcast(new Intent(BROADCAST_PLAYSTATECHANGED)); handlePlayState(); } /** * Pause playback. */ public void pause() { mPlayState = PLAYBACKSERVICE_PLAYSTATE_PAUSED; sendBroadcast(new Intent(BROADCAST_PLAYSTATECHANGED)); handlePlayState(); } /** * Start playing the next Track. */ public void next() { Track track = mCurrentPlaylist.getNextTrack(); if (track != null) { try { setCurrentTrack(track); } catch (IOException e) { Log.e(TAG, "next(): " + IOException.class.getName() + ": " + e.getLocalizedMessage()); } } updatePlayingNotification(); } /** * Play the previous track. */ public void previous() { Track track = mCurrentPlaylist.getPreviousTrack(); if (track != null) { try { setCurrentTrack(track); } catch (IOException e) { Log.e(TAG, "previous(): " + IOException.class.getName() + ": " + e.getLocalizedMessage()); } } updatePlayingNotification(); } /* (non-Javadoc) * @see android.media.MediaPlayer.OnErrorListener#onError(android.media.MediaPlayer, int, int) */ @Override public boolean onError(MediaPlayer mp, int what, int extra) { String whatString = "CODE UNSPECIFIED"; switch (what) { case MediaPlayer.MEDIA_ERROR_UNKNOWN: whatString = "MEDIA_ERROR_UNKNOWN"; break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: whatString = "MEDIA_ERROR_SERVER_DIED"; } Log.e(TAG, "onError - " + whatString); next(); return false; } /* (non-Javadoc) * @see android.media.MediaPlayer.OnCompletionListener#onCompletion(android.media.MediaPlayer) */ @Override public void onCompletion(MediaPlayer mp) { if (mCurrentPlaylist == null) { stop(); return; } Track track = mCurrentPlaylist.getNextTrack(); if (track != null) { try { setCurrentTrack(track); } catch (IOException e) { e.printStackTrace(); } } else stop(); } /* (non-Javadoc) * @see android.media.MediaPlayer.OnPreparedListener#onPrepared(android.media.MediaPlayer) */ @Override public void onPrepared(MediaPlayer mp) { Log.d(TAG, "Mediaplayer is prepared."); mIsPreparing = false; handlePlayState(); } /** * Returns whether this PlaybackService is currently playing media. */ public boolean isPlaying() { return mPlayState == PLAYBACKSERVICE_PLAYSTATE_PLAYING; } /** * @return Whether or not the mediaPlayer currently prepares a track */ public boolean isPreparing() { return mIsPreparing; } /** * Get the current Playlist * * @return */ public Playlist getCurrentPlaylist() { return mCurrentPlaylist; } /** * Set the current Playlist to playlist and set the current Track to the * Playlist's current Track. * * @param playlist * @throws IOException */ public void setCurrentPlaylist(Playlist playlist) throws IOException { mCurrentPlaylist = playlist; setCurrentTrack(mCurrentPlaylist.getCurrentTrack()); sendBroadcast(new Intent(BROADCAST_PLAYLISTCHANGED)); } /** * Set the current playlist to shuffle mode. * * @param shuffled */ public void setShuffled(boolean shuffled) { mCurrentPlaylist.setShuffled(shuffled); sendBroadcast(new Intent(BROADCAST_PLAYLISTCHANGED)); } /** * Set the current playlist to repeat mode. * * @param repeating */ public void setRepeating(boolean repeating) { mCurrentPlaylist.setRepeating(repeating); sendBroadcast(new Intent(BROADCAST_PLAYLISTCHANGED)); } /** * Get the current Track * * @return */ public Track getCurrentTrack() { if (mCurrentPlaylist == null) return null; return mCurrentPlaylist.getCurrentTrack(); } /** * This method sets the current track and prepares it for playback. * * @param track * @throws IOException */ public void setCurrentTrack(Track track) throws IOException { if (!mIsPreparing) { mMediaPlayer.reset(); } else { mMediaPlayer.release(); initMediaPlayer(); } mMediaPlayer.setDataSource(track.getPath()); mMediaPlayer.prepareAsync(); mIsPreparing = true; sendBroadcast(new Intent(BROADCAST_NEWTRACK)); } /** * Create or update an ongoing notification */ private void updatePlayingNotification() { Track track = getCurrentTrack(); + if (track == null) + return; Resources resources = getResources(); Bitmap albumArtTemp; String albumName = ""; String artistName = ""; if (track.getAlbum() != null) albumName = track.getAlbum().getName(); if (track.getArtist() != null) artistName = track.getArtist().getName(); if (track.getAlbum() != null && track.getAlbum().getAlbumArt() != null) albumArtTemp = track.getAlbum().getAlbumArt(); else albumArtTemp = BitmapFactory.decodeResource(resources, R.drawable.no_album_art_placeholder); Bitmap largeAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, 256, 256, false); Bitmap smallAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false); Intent intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE); PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_NEXT); PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_EXIT); PendingIntent exitPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); RemoteViews smallNotificationView; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small); smallNotificationView.setImageViewBitmap(R.id.notification_small_imageview_albumart, smallAlbumArt); } else smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small_compat); smallNotificationView.setTextViewText(R.id.notification_small_textview, track.getName()); if (albumName == "") smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName); else smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName + " - " + albumName); if (isPlaying()) smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_pause); else smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_play); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_playpause, playPausePendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_next, nextPendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_exit, exitPendingIntent); NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle( artistName).setContentText(track.getName()).setLargeIcon(smallAlbumArt).setOngoing(true).setPriority( NotificationCompat.PRIORITY_MAX).setContent(smallNotificationView); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(PlaybackActivity.class); Intent notificationIntent = getIntent(this, PlaybackActivity.class); stackBuilder.addNextIntent(notificationIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); Notification notification = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { RemoteViews largeNotificationView = new RemoteViews(getPackageName(), R.layout.notification_large); largeNotificationView.setImageViewBitmap(R.id.notification_large_imageview_albumart, largeAlbumArt); largeNotificationView.setTextViewText(R.id.notification_large_textview, track.getName()); largeNotificationView.setTextViewText(R.id.notification_large_textview2, artistName); largeNotificationView.setTextViewText(R.id.notification_large_textview3, albumName); if (isPlaying()) largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_pause); else largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_play); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_previous, previousPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_playpause, playPausePendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_next, nextPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_exit, exitPendingIntent); notification.bigContentView = largeNotificationView; } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(PLAYBACKSERVICE_NOTIFICATION_ID, notification); } /** * Return the {@link Intent} defined by the given parameters * * @param context the context with which the intent will be created * @param cls the class which contains the activity to launch * @return the created intent */ private static Intent getIntent(Context context, Class<?> cls) { Intent intent = new Intent(context, cls); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); return intent; } /** * Returns the position of playback in the current Track. */ public int getPosition() { int position = 0; try { position = mMediaPlayer.getCurrentPosition(); } catch (IllegalStateException e) { } return position; } /** * Seeks to position msec * @param msec */ public void seekTo(int msec) { mMediaPlayer.seekTo(msec); } }
true
true
private void updatePlayingNotification() { Track track = getCurrentTrack(); Resources resources = getResources(); Bitmap albumArtTemp; String albumName = ""; String artistName = ""; if (track.getAlbum() != null) albumName = track.getAlbum().getName(); if (track.getArtist() != null) artistName = track.getArtist().getName(); if (track.getAlbum() != null && track.getAlbum().getAlbumArt() != null) albumArtTemp = track.getAlbum().getAlbumArt(); else albumArtTemp = BitmapFactory.decodeResource(resources, R.drawable.no_album_art_placeholder); Bitmap largeAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, 256, 256, false); Bitmap smallAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false); Intent intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE); PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_NEXT); PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_EXIT); PendingIntent exitPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); RemoteViews smallNotificationView; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small); smallNotificationView.setImageViewBitmap(R.id.notification_small_imageview_albumart, smallAlbumArt); } else smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small_compat); smallNotificationView.setTextViewText(R.id.notification_small_textview, track.getName()); if (albumName == "") smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName); else smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName + " - " + albumName); if (isPlaying()) smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_pause); else smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_play); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_playpause, playPausePendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_next, nextPendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_exit, exitPendingIntent); NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle( artistName).setContentText(track.getName()).setLargeIcon(smallAlbumArt).setOngoing(true).setPriority( NotificationCompat.PRIORITY_MAX).setContent(smallNotificationView); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(PlaybackActivity.class); Intent notificationIntent = getIntent(this, PlaybackActivity.class); stackBuilder.addNextIntent(notificationIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); Notification notification = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { RemoteViews largeNotificationView = new RemoteViews(getPackageName(), R.layout.notification_large); largeNotificationView.setImageViewBitmap(R.id.notification_large_imageview_albumart, largeAlbumArt); largeNotificationView.setTextViewText(R.id.notification_large_textview, track.getName()); largeNotificationView.setTextViewText(R.id.notification_large_textview2, artistName); largeNotificationView.setTextViewText(R.id.notification_large_textview3, albumName); if (isPlaying()) largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_pause); else largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_play); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_previous, previousPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_playpause, playPausePendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_next, nextPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_exit, exitPendingIntent); notification.bigContentView = largeNotificationView; } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(PLAYBACKSERVICE_NOTIFICATION_ID, notification); }
private void updatePlayingNotification() { Track track = getCurrentTrack(); if (track == null) return; Resources resources = getResources(); Bitmap albumArtTemp; String albumName = ""; String artistName = ""; if (track.getAlbum() != null) albumName = track.getAlbum().getName(); if (track.getArtist() != null) artistName = track.getArtist().getName(); if (track.getAlbum() != null && track.getAlbum().getAlbumArt() != null) albumArtTemp = track.getAlbum().getAlbumArt(); else albumArtTemp = BitmapFactory.decodeResource(resources, R.drawable.no_album_art_placeholder); Bitmap largeAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, 256, 256, false); Bitmap smallAlbumArt = Bitmap.createScaledBitmap(albumArtTemp, resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false); Intent intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_PLAYPAUSE); PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_NEXT); PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); intent = new Intent(BROADCAST_NOTIFICATIONINTENT_EXIT); PendingIntent exitPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); RemoteViews smallNotificationView; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small); smallNotificationView.setImageViewBitmap(R.id.notification_small_imageview_albumart, smallAlbumArt); } else smallNotificationView = new RemoteViews(getPackageName(), R.layout.notification_small_compat); smallNotificationView.setTextViewText(R.id.notification_small_textview, track.getName()); if (albumName == "") smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName); else smallNotificationView.setTextViewText(R.id.notification_small_textview2, artistName + " - " + albumName); if (isPlaying()) smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_pause); else smallNotificationView.setImageViewResource(R.id.notification_small_imageview_playpause, R.drawable.ic_player_play); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_playpause, playPausePendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_next, nextPendingIntent); smallNotificationView.setOnClickPendingIntent(R.id.notification_small_imageview_exit, exitPendingIntent); NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle( artistName).setContentText(track.getName()).setLargeIcon(smallAlbumArt).setOngoing(true).setPriority( NotificationCompat.PRIORITY_MAX).setContent(smallNotificationView); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(PlaybackActivity.class); Intent notificationIntent = getIntent(this, PlaybackActivity.class); stackBuilder.addNextIntent(notificationIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); Notification notification = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { RemoteViews largeNotificationView = new RemoteViews(getPackageName(), R.layout.notification_large); largeNotificationView.setImageViewBitmap(R.id.notification_large_imageview_albumart, largeAlbumArt); largeNotificationView.setTextViewText(R.id.notification_large_textview, track.getName()); largeNotificationView.setTextViewText(R.id.notification_large_textview2, artistName); largeNotificationView.setTextViewText(R.id.notification_large_textview3, albumName); if (isPlaying()) largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_pause); else largeNotificationView.setImageViewResource(R.id.notification_large_imageview_playpause, R.drawable.ic_player_play); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_previous, previousPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_playpause, playPausePendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_next, nextPendingIntent); largeNotificationView.setOnClickPendingIntent(R.id.notification_large_imageview_exit, exitPendingIntent); notification.bigContentView = largeNotificationView; } NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(PLAYBACKSERVICE_NOTIFICATION_ID, notification); }
diff --git a/src/main/java/com/metaweb/gridworks/expr/ExpressionUtils.java b/src/main/java/com/metaweb/gridworks/expr/ExpressionUtils.java index f5b8574e..f5928f75 100644 --- a/src/main/java/com/metaweb/gridworks/expr/ExpressionUtils.java +++ b/src/main/java/com/metaweb/gridworks/expr/ExpressionUtils.java @@ -1,66 +1,70 @@ package com.metaweb.gridworks.expr; import java.util.Properties; import com.metaweb.gridworks.model.Cell; import com.metaweb.gridworks.model.Project; import com.metaweb.gridworks.model.Row; public class ExpressionUtils { static public Properties createBindings(Project project) { Properties bindings = new Properties(); bindings.put("true", true); bindings.put("false", false); bindings.put("project", project); return bindings; } static public void bind(Properties bindings, Row row, int rowIndex, Cell cell) { bindings.put("row", row); bindings.put("rowIndex", rowIndex); bindings.put("cells", row.getField("cells", bindings)); if (cell == null) { bindings.remove("cell"); bindings.remove("value"); } else { bindings.put("cell", cell); - bindings.put("value", cell.value); + if (cell.value == null) { + bindings.remove("value"); + } else { + bindings.put("value", cell.value); + } } } static public boolean isError(Object o) { return o != null && o instanceof EvalError; } /* static public boolean isBlank(Object o) { return o == null || (o instanceof String && ((String) o).length() == 0); } */ static public boolean isNonBlankData(Object o) { return o != null && !(o instanceof EvalError) && (!(o instanceof String) || ((String) o).length() > 0); } static public boolean isTrue(Object o) { return o != null && (o instanceof Boolean ? ((Boolean) o).booleanValue() : Boolean.parseBoolean(o.toString())); } static public boolean sameValue(Object v1, Object v2) { if (v1 == null) { return (v2 == null) || (v2 instanceof String && ((String) v2).length() == 0); } else if (v2 == null) { return (v1 == null) || (v1 instanceof String && ((String) v1).length() == 0); } else { return v1.equals(v2); } } }
true
true
static public void bind(Properties bindings, Row row, int rowIndex, Cell cell) { bindings.put("row", row); bindings.put("rowIndex", rowIndex); bindings.put("cells", row.getField("cells", bindings)); if (cell == null) { bindings.remove("cell"); bindings.remove("value"); } else { bindings.put("cell", cell); bindings.put("value", cell.value); } }
static public void bind(Properties bindings, Row row, int rowIndex, Cell cell) { bindings.put("row", row); bindings.put("rowIndex", rowIndex); bindings.put("cells", row.getField("cells", bindings)); if (cell == null) { bindings.remove("cell"); bindings.remove("value"); } else { bindings.put("cell", cell); if (cell.value == null) { bindings.remove("value"); } else { bindings.put("value", cell.value); } } }
diff --git a/src/main/java/kniemkiewicz/jqblocks/ingame/level/enemies/RoamingEnemiesController.java b/src/main/java/kniemkiewicz/jqblocks/ingame/level/enemies/RoamingEnemiesController.java index bb85e3d..23a6c12 100644 --- a/src/main/java/kniemkiewicz/jqblocks/ingame/level/enemies/RoamingEnemiesController.java +++ b/src/main/java/kniemkiewicz/jqblocks/ingame/level/enemies/RoamingEnemiesController.java @@ -1,126 +1,130 @@ package kniemkiewicz.jqblocks.ingame.level.enemies; import kniemkiewicz.jqblocks.Configuration; import kniemkiewicz.jqblocks.ingame.PointOfView; import kniemkiewicz.jqblocks.ingame.World; import kniemkiewicz.jqblocks.ingame.object.hp.KillablePhysicalObject; import kniemkiewicz.jqblocks.ingame.content.player.PlayerController; import kniemkiewicz.jqblocks.ingame.object.background.BackgroundElement; import kniemkiewicz.jqblocks.ingame.object.background.Backgrounds; import kniemkiewicz.jqblocks.ingame.object.background.WorkplaceBackgroundElement; import kniemkiewicz.jqblocks.ingame.object.workplace.WorkplaceDefinition; import kniemkiewicz.jqblocks.util.BeanName; import kniemkiewicz.jqblocks.util.GeometryUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * User: knie * Date: 9/3/12 */ @Component public final class RoamingEnemiesController { public static Log logger = LogFactory.getLog(RoamingEnemiesController.class); @Autowired PlayerController playerController; @Autowired Backgrounds backgrounds; @Autowired TownBiome townBiome; @Autowired GrassBiome grassBiome; @Autowired World world; @Autowired Configuration configuration; @Autowired PointOfView pointOfView; static final float MAX_PURSUIT_DISTANCE_SCREENS = 1; int MAX_ACTIVE_ENEMIES = -1; static final float TOWN_RADIUS_FROM_FIREPLACE = 500; @PostConstruct void init() { MAX_ACTIVE_ENEMIES = configuration.getInt("RoamingEnemiesController.MAX_ACTIVE_ENEMIES", 10); } List<KillablePhysicalObject> activeEnemies = new LinkedList<KillablePhysicalObject>(); // We cache biome, until next call to update() Biome cachedBiome = null; public Biome getCurrentBiome() { if (cachedBiome == null) { cachedBiome = calculateCurrentBiome(); assert cachedBiome != null; } return cachedBiome; } static boolean isNearFireplace(Shape shape, Backgrounds backgrounds) { Rectangle aroundShape = GeometryUtils.getRectangleCenteredOn(shape, 2 * TOWN_RADIUS_FROM_FIREPLACE, 2 * TOWN_RADIUS_FROM_FIREPLACE); Iterator<BackgroundElement> it = backgrounds.intersects(aroundShape); while (it.hasNext()) { BackgroundElement el = it.next(); if (el instanceof WorkplaceBackgroundElement) { WorkplaceBackgroundElement wbe = (WorkplaceBackgroundElement) el; if (wbe.getWorkplace().getBeanName().equals("fireplace")) { return true; } } } return false; } private Biome calculateCurrentBiome() { assert TOWN_RADIUS_FROM_FIREPLACE >= 0; // "fireplace" should be a valid bean name assert world.getSpringBeanProvider().getBean(new BeanName<WorkplaceDefinition>(WorkplaceDefinition.class, "fireplace"), false) != null; if (isNearFireplace(playerController.getPlayer().getShape(), backgrounds)) return townBiome; return grassBiome; } private boolean isTooFar(Shape player, Shape object) { return Math.abs(player.getCenterX() - object.getCenterX()) > MAX_PURSUIT_DISTANCE_SCREENS * pointOfView.getWindowWidth() || Math.abs(player.getCenterY() - object.getCenterY()) > MAX_PURSUIT_DISTANCE_SCREENS * pointOfView.getWindowHeight(); } public void update(int delta) { assert MAX_ACTIVE_ENEMIES >= 0; cachedBiome = null; Rectangle playerShape = playerController.getPlayer().getShape(); Iterator<KillablePhysicalObject> it = activeEnemies.iterator(); while (it.hasNext()) { KillablePhysicalObject ob = it.next(); - if (ob.getHp().isDead() || isTooFar(playerShape, ob.getShape())) { + if (ob.getHp().isDead()) { it.remove(); } + if (isTooFar(playerShape, ob.getShape())) { + it.remove(); + world.killMovingObject(ob); + } } if (activeEnemies.size() < MAX_ACTIVE_ENEMIES) { KillablePhysicalObject ob = getCurrentBiome().maybeGenerateNewEnemy(delta, playerController.getPlayer()); if (ob != null) { activeEnemies.add(ob); } } } }
false
true
public void update(int delta) { assert MAX_ACTIVE_ENEMIES >= 0; cachedBiome = null; Rectangle playerShape = playerController.getPlayer().getShape(); Iterator<KillablePhysicalObject> it = activeEnemies.iterator(); while (it.hasNext()) { KillablePhysicalObject ob = it.next(); if (ob.getHp().isDead() || isTooFar(playerShape, ob.getShape())) { it.remove(); } } if (activeEnemies.size() < MAX_ACTIVE_ENEMIES) { KillablePhysicalObject ob = getCurrentBiome().maybeGenerateNewEnemy(delta, playerController.getPlayer()); if (ob != null) { activeEnemies.add(ob); } } }
public void update(int delta) { assert MAX_ACTIVE_ENEMIES >= 0; cachedBiome = null; Rectangle playerShape = playerController.getPlayer().getShape(); Iterator<KillablePhysicalObject> it = activeEnemies.iterator(); while (it.hasNext()) { KillablePhysicalObject ob = it.next(); if (ob.getHp().isDead()) { it.remove(); } if (isTooFar(playerShape, ob.getShape())) { it.remove(); world.killMovingObject(ob); } } if (activeEnemies.size() < MAX_ACTIVE_ENEMIES) { KillablePhysicalObject ob = getCurrentBiome().maybeGenerateNewEnemy(delta, playerController.getPlayer()); if (ob != null) { activeEnemies.add(ob); } } }
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ExternalMusicTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ExternalMusicTest.java index e15646030..3911886cf 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ExternalMusicTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ExternalMusicTest.java @@ -1,45 +1,45 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.tests.utils.GdxTest; /** Tests playing back audio from the external storage. * @author mzechner */ public class ExternalMusicTest extends GdxTest { @Override public void create () { // copy an internal mp3 to the external storage - FileHandle src = Gdx.files.internal("data/iron.mp3"); + FileHandle src = Gdx.files.internal("data/8.12.mp3"); FileHandle dst = Gdx.files.external("8.12.mp3"); src.copyTo(dst); // create a music instance and start playback Music music = Gdx.audio.newMusic(dst); music.play(); } @Override public void dispose () { // delete the copy on the external storage Gdx.files.external("8.12.mp3").delete(); } }
true
true
public void create () { // copy an internal mp3 to the external storage FileHandle src = Gdx.files.internal("data/iron.mp3"); FileHandle dst = Gdx.files.external("8.12.mp3"); src.copyTo(dst); // create a music instance and start playback Music music = Gdx.audio.newMusic(dst); music.play(); }
public void create () { // copy an internal mp3 to the external storage FileHandle src = Gdx.files.internal("data/8.12.mp3"); FileHandle dst = Gdx.files.external("8.12.mp3"); src.copyTo(dst); // create a music instance and start playback Music music = Gdx.audio.newMusic(dst); music.play(); }
diff --git a/android/src/ru/net/jimm/Environment.java b/android/src/ru/net/jimm/Environment.java index 1a7b89e..126b32a 100644 --- a/android/src/ru/net/jimm/Environment.java +++ b/android/src/ru/net/jimm/Environment.java @@ -1,104 +1,104 @@ package ru.net.jimm; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.Sensor; import android.hardware.SensorManager; import android.provider.Settings; import org.microemu.android.util.AndroidLoggerAppender; import org.microemu.log.Logger; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Locale; /** * Created with IntelliJ IDEA. * <p/> * Date: 27.04.13 12:44 * * @author vladimir */ public class Environment { public static void initLogger() { Logger.removeAllAppenders(); Logger.setLocationEnabled(false); Logger.addAppender(new AndroidLoggerAppender()); System.setOut(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { - Logger.debug(line.toString()); if (line.length() > 0) { - line.delete(0, line.length() - 1); + Logger.debug(line.toString()); + line.setLength(0); } } else { line.append((char) oneByte); } } })); System.setErr(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { - Logger.debug(line.toString()); if (line.length() > 0) { - line.delete(0, line.length() - 1); + Logger.debug(line.toString()); + line.setLength(0); } } else { line.append((char) oneByte); } } })); } public static void setup(Activity activity) { System.setProperty("microedition.platform", "microemu-android"); System.setProperty("microedition.configuration", "CLDC-1.1"); System.setProperty("microedition.profiles", "MIDP-2.0"); System.setProperty("microedition.locale", Locale.getDefault().toString()); System.setProperty("device.manufacturer", android.os.Build.BRAND); System.setProperty("device.model", android.os.Build.MODEL); System.setProperty("device.software.version", android.os.Build.VERSION.RELEASE); // photo if (hasCamera(activity)) { System.setProperty("video.snapshot.encodings", "yes"); } if (hasAccelerometer(activity)) { System.setProperty("device.accelerometer", "yes"); } } private static boolean hasAccelerometer(Activity activity) { boolean defValue = false; try { SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); if (null == sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) { return false; } defValue = true; return 1 == Settings.System.getInt(activity.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION); } catch (Throwable e) { return defValue; } } private static boolean hasCamera(Activity activity) { try { return (activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)); } catch (Throwable e) { return false; } } }
false
true
public static void initLogger() { Logger.removeAllAppenders(); Logger.setLocationEnabled(false); Logger.addAppender(new AndroidLoggerAppender()); System.setOut(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { Logger.debug(line.toString()); if (line.length() > 0) { line.delete(0, line.length() - 1); } } else { line.append((char) oneByte); } } })); System.setErr(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { Logger.debug(line.toString()); if (line.length() > 0) { line.delete(0, line.length() - 1); } } else { line.append((char) oneByte); } } })); }
public static void initLogger() { Logger.removeAllAppenders(); Logger.setLocationEnabled(false); Logger.addAppender(new AndroidLoggerAppender()); System.setOut(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { if (line.length() > 0) { Logger.debug(line.toString()); line.setLength(0); } } else { line.append((char) oneByte); } } })); System.setErr(new PrintStream(new OutputStream() { StringBuffer line = new StringBuffer(); @Override public void write(int oneByte) throws IOException { if (((char) oneByte) == '\n') { if (line.length() > 0) { Logger.debug(line.toString()); line.setLength(0); } } else { line.append((char) oneByte); } } })); }
diff --git a/src/com/android/browser/DownloadHandler.java b/src/com/android/browser/DownloadHandler.java index dee10ae..208d4ce 100644 --- a/src/com/android/browser/DownloadHandler.java +++ b/src/com/android/browser/DownloadHandler.java @@ -1,232 +1,241 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import android.app.Activity; import android.app.AlertDialog; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.net.WebAddress; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import android.webkit.CookieManager; import android.webkit.URLUtil; import android.widget.Toast; /** * Handle download requests */ public class DownloadHandler { private static final boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; private static final String LOGTAG = "DLHandler"; /** * Notify the host application a download should be done, or that * the data should be streamed if a streaming viewer is available. * @param activity Activity requesting the download. * @param url The full url to the content that should be downloaded * @param userAgent User agent of the downloading application. * @param contentDisposition Content-disposition http header, if present. * @param mimetype The mimetype of the content reported by the server * @param referer The referer associated with the downloaded url * @param privateBrowsing If the request is coming from a private browsing tab. */ public static void onDownloadStart(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { // if we're dealing wih A/V content that's not explicitly marked // for download, check if it's streamable. if (contentDisposition == null || !contentDisposition.regionMatches( true, 0, "attachment", 0, 10)) { // query the package manager to see if there's a registered handler // that matches. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), mimetype); ResolveInfo info = activity.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { ComponentName myName = activity.getComponentName(); // If we resolved to ourselves, we don't want to attempt to // load the url only to try and download it again. if (!myName.getPackageName().equals( info.activityInfo.packageName) || !myName.getClassName().equals( info.activityInfo.name)) { // someone (other than us) knows how to handle this mime // type with this scheme, don't download. try { activity.startActivity(intent); return; } catch (ActivityNotFoundException ex) { if (LOGD_ENABLED) { Log.d(LOGTAG, "activity not found for " + mimetype + " over " + Uri.parse(url).getScheme(), ex); } // Best behavior is to fall back to a download in this // case } } } } onDownloadStartNoStream(activity, url, userAgent, contentDisposition, mimetype, referer, privateBrowsing); } // This is to work around the fact that java.net.URI throws Exceptions // instead of just encoding URL's properly // Helper method for onDownloadStartNoStream private static String encodePath(String path) { char[] chars = path.toCharArray(); boolean needed = false; for (char c : chars) { if (c == '[' || c == ']' || c == '|') { needed = true; break; } } if (needed == false) { return path; } StringBuilder sb = new StringBuilder(""); for (char c : chars) { if (c == '[' || c == ']' || c == '|') { sb.append('%'); sb.append(Integer.toHexString(c)); } else { sb.append(c); } } return sb.toString(); } /** * Notify the host application a download should be done, even if there * is a streaming viewer available for thise type. * @param activity Activity requesting the download. * @param url The full url to the content that should be downloaded * @param userAgent User agent of the downloading application. * @param contentDisposition Content-disposition http header, if present. * @param mimetype The mimetype of the content reported by the server * @param referer The referer associated with the downloaded url * @param privateBrowsing If the request is coming from a private browsing tab. */ /*package */ static void onDownloadStartNoStream(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity) .setTitle(title) .setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); - // let this downloaded file be scanned by MediaScanner - so that it can + try { + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); + } catch (IllegalStateException ex) { + // This only happens when directory Downloads can't be created or it isn't a directory + // this is most commonly due to temporary problems with sdcard so show appropriate string + Log.w(LOGTAG, "Exception trying to create Download dir:", ex); + Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, + Toast.LENGTH_SHORT).show(); + return; + } + // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.addRequestHeader("Referer", referer); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("Browser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT) .show(); } }
true
true
/*package */ static void onDownloadStartNoStream(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity) .setTitle(title) .setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.addRequestHeader("Referer", referer); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("Browser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT) .show(); }
/*package */ static void onDownloadStartNoStream(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity) .setTitle(title) .setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); } catch (IllegalStateException ex) { // This only happens when directory Downloads can't be created or it isn't a directory // this is most commonly due to temporary problems with sdcard so show appropriate string Log.w(LOGTAG, "Exception trying to create Download dir:", ex); Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show(); return; } // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.addRequestHeader("Referer", referer); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("Browser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT) .show(); }
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaExceptionBreakpoint.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaExceptionBreakpoint.java index fc357817e..9bd67d514 100644 --- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaExceptionBreakpoint.java +++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaExceptionBreakpoint.java @@ -1,284 +1,284 @@ package org.eclipse.jdt.internal.debug.core; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugException; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.debug.core.IJavaExceptionBreakpoint; import com.sun.jdi.ReferenceType; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.VirtualMachine; import com.sun.jdi.request.EventRequest; import com.sun.jdi.request.ExceptionRequest; public class JavaExceptionBreakpoint extends JavaBreakpoint implements IJavaExceptionBreakpoint { private static final String JAVA_EXCEPTION_BREAKPOINT= "org.eclipse.jdt.debug.javaExceptionBreakpointMarker"; //$NON-NLS-1$ /** * Exception breakpoint attribute storing the suspend on caught value * (value <code>"caught"</code>). This attribute is stored as a <code>boolean</code>. * When this attribute is <code>true</code>, a caught exception of the associated * type will cause excecution to suspend . */ protected static final String CAUGHT = "caught"; //$NON-NLS-1$ /** * Exception breakpoint attribute storing the suspend on uncaught value * (value <code>"uncaught"</code>). This attribute is stored as a * <code>boolean</code>. When this attribute is <code>true</code>, an uncaught * exception of the associated type will cause excecution to suspend. . */ protected static final String UNCAUGHT = "uncaught"; //$NON-NLS-1$ /** * Exception breakpoint attribute storing the checked value (value <code>"checked"</code>). * This attribute is stored as a <code>boolean</code>, indicating whether an * exception is a checked exception. */ protected static final String CHECKED = "checked"; //$NON-NLS-1$ // Attribute strings protected static final String[] fgExceptionBreakpointAttributes= new String[]{CHECKED, TYPE_HANDLE}; public JavaExceptionBreakpoint() { } /** * Creates and returns an exception breakpoint for the * given (throwable) type. Caught and uncaught specify where the exception * should cause thread suspensions - that is, in caught and/or uncaught locations. * Checked indicates if the given exception is a checked exception. * Note: the breakpoint is not added to the breakpoint manager * - it is merely created. * * @param type the exception for which to create the breakpoint * @param caught whether to suspend in caught locations * @param uncaught whether to suspend in uncaught locations * @param checked whether the exception is a checked exception * @return a java exception breakpoint * @exception DebugException if unable to create the associated marker due * to a lower level exception. */ public JavaExceptionBreakpoint(final IType exception, final boolean caught, final boolean uncaught, final boolean checked) throws DebugException { IWorkspaceRunnable wr= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { IResource resource= null; resource= exception.getUnderlyingResource(); if (resource == null) { resource= exception.getJavaProject().getProject(); } // create the marker - fMarker= resource.createMarker(JAVA_EXCEPTION_BREAKPOINT); + setMarker(resource.createMarker(JAVA_EXCEPTION_BREAKPOINT)); // configure the standard attributes setEnabled(true); // configure caught, uncaught, checked, and the type attributes setCaughtAndUncaught(caught, uncaught); setTypeAndChecked(exception, checked); // configure the marker as a Java marker IMarker marker = ensureMarker(); Map attributes= marker.getAttributes(); JavaCore.addJavaElementMarkerAttributes(attributes, exception); marker.setAttributes(attributes); addToBreakpointManager(); } }; run(wr); } /** * Sets the exception type on which this breakpoint is installed and whether * or not that exception is a checked exception. */ protected void setTypeAndChecked(IType exception, boolean checked) throws CoreException { String handle = exception.getHandleIdentifier(); Object[] values= new Object[]{new Boolean(checked), handle}; ensureMarker().setAttributes(fgExceptionBreakpointAttributes, values); } /** * Sets the values for whether this breakpoint will * suspend execution when the associated exception is thrown * and caught or not caught.. */ public void setCaughtAndUncaught(boolean caught, boolean uncaught) throws CoreException { Object[] values= new Object[]{new Boolean(caught), new Boolean(uncaught)}; String[] attributes= new String[]{CAUGHT, UNCAUGHT}; ensureMarker().setAttributes(attributes, values); } /** * Creates a request in the given target to suspend when the given exception * type is thrown. The request is returned installed, configured, and enabled * as appropriate for this breakpoint. */ protected EventRequest newRequest(JDIDebugTarget target, ReferenceType type) throws CoreException { if (!isCaught() && !isUncaught()) { return null; } ExceptionRequest request= null; try { request= target.getEventRequestManager().createExceptionRequest(type, isCaught(), isUncaught()); configureRequest(request); } catch (VMDisconnectedException e) { if (target.isTerminated() || target.isDisconnected()) { return null; } JDIDebugPlugin.logError(e); return null; } catch (RuntimeException e) { JDIDebugPlugin.logError(e); return null; } return request; } /** * Enable this exception breakpoint. * * If the exception breakpoint is not catching caught or uncaught, * turn both modes on. If this isn't done, the resulting * state (enabled with caught and uncaught both disabled) * is ambiguous. */ public void setEnabled(boolean enabled) throws CoreException { super.setEnabled(enabled); if (isEnabled()) { if (!(isCaught() || isUncaught())) { setCaughtAndUncaught(true, true); } } } /** * @see IJavaExceptionBreakpoint#isCaught() */ public boolean isCaught() throws CoreException { return ensureMarker().getAttribute(CAUGHT, false); } /** * @see IJavaExceptionBreakpoint#setCaught(boolean) */ public void setCaught(boolean caught) throws CoreException { if (caught == isCaught()) { return; } ensureMarker().setAttribute(CAUGHT, caught); if (caught && !isEnabled()) { setEnabled(true); } else if (!(caught || isUncaught())) { setEnabled(false); } } /** * @see IJavaExceptionBreakpoint#isUncaught() */ public boolean isUncaught() throws CoreException { return ensureMarker().getAttribute(UNCAUGHT, false); } /** * @see IJavaExceptionBreakpoint#setUncaught(boolean) */ public void setUncaught(boolean uncaught) throws CoreException { if (uncaught == isUncaught()) { return; } ensureMarker().setAttribute(UNCAUGHT, uncaught); if (uncaught && !isEnabled()) { setEnabled(true); } else if (!(uncaught || isCaught())) { setEnabled(false); } } /** * @see IJavaExceptionBreakpoint#isChecked() */ public boolean isChecked() throws CoreException { return ensureMarker().getAttribute(CHECKED, false); } /** * Update the hit count of an <code>EventRequest</code>. Return a new request with * the appropriate settings. */ protected EventRequest updateHitCount(EventRequest request, JDIDebugTarget target) throws CoreException { // if the hit count has changed, or the request has expired and is being re-enabled, // create a new request if (hasHitCountChanged(request) || (isExpired(request) && isEnabled())) { request= createUpdatedExceptionRequest(target, (ExceptionRequest)request); } return request; } /** * @see JavaBreakpoint#updateRequest(EventRequest, JDIDebugTarget) */ protected void updateRequest(EventRequest request, JDIDebugTarget target) throws CoreException { updateEnabledState(request); EventRequest newRequest = updateHitCount(request, target); newRequest= updateCaughtState(newRequest,target); if (newRequest != null && newRequest != request) { replaceRequest(target, request, newRequest); request = newRequest; } } /** * Return a request that will suspend execution when a caught and/or uncaught * exception is thrown as is appropriate for the current state of this breakpoint. */ protected EventRequest updateCaughtState(EventRequest req, JDIDebugTarget target) throws CoreException { if(!(req instanceof ExceptionRequest)) { return req; } ExceptionRequest request= (ExceptionRequest) req; if (request.notifyCaught() != isCaught() || request.notifyUncaught() != isUncaught()) { request= createUpdatedExceptionRequest(target, (ExceptionRequest)request); } return request; } /** * Create a request that reflects the current state of this breakpoint. * The new request will be installed in the same type as the given * request. */ protected ExceptionRequest createUpdatedExceptionRequest(JDIDebugTarget target, ExceptionRequest request) throws CoreException{ try { ReferenceType exClass = ((ExceptionRequest)request).exception(); request = (ExceptionRequest) newRequest(target, exClass); } catch (VMDisconnectedException e) { if (target.isTerminated() || target.isDisconnected()) { return request; } JDIDebugPlugin.logError(e); } catch (RuntimeException e) { JDIDebugPlugin.logError(e); } return request; } }
true
true
public JavaExceptionBreakpoint(final IType exception, final boolean caught, final boolean uncaught, final boolean checked) throws DebugException { IWorkspaceRunnable wr= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { IResource resource= null; resource= exception.getUnderlyingResource(); if (resource == null) { resource= exception.getJavaProject().getProject(); } // create the marker fMarker= resource.createMarker(JAVA_EXCEPTION_BREAKPOINT); // configure the standard attributes setEnabled(true); // configure caught, uncaught, checked, and the type attributes setCaughtAndUncaught(caught, uncaught); setTypeAndChecked(exception, checked); // configure the marker as a Java marker IMarker marker = ensureMarker(); Map attributes= marker.getAttributes(); JavaCore.addJavaElementMarkerAttributes(attributes, exception); marker.setAttributes(attributes); addToBreakpointManager(); } }; run(wr); }
public JavaExceptionBreakpoint(final IType exception, final boolean caught, final boolean uncaught, final boolean checked) throws DebugException { IWorkspaceRunnable wr= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { IResource resource= null; resource= exception.getUnderlyingResource(); if (resource == null) { resource= exception.getJavaProject().getProject(); } // create the marker setMarker(resource.createMarker(JAVA_EXCEPTION_BREAKPOINT)); // configure the standard attributes setEnabled(true); // configure caught, uncaught, checked, and the type attributes setCaughtAndUncaught(caught, uncaught); setTypeAndChecked(exception, checked); // configure the marker as a Java marker IMarker marker = ensureMarker(); Map attributes= marker.getAttributes(); JavaCore.addJavaElementMarkerAttributes(attributes, exception); marker.setAttributes(attributes); addToBreakpointManager(); } }; run(wr); }
diff --git a/src/org/jacorb/ir/QueryIR.java b/src/org/jacorb/ir/QueryIR.java index 6cc9218b..e1916ec5 100644 --- a/src/org/jacorb/ir/QueryIR.java +++ b/src/org/jacorb/ir/QueryIR.java @@ -1,71 +1,72 @@ package org.jacorb.ir; /* * JacORB - a free Java ORB * * Copyright (C) 1997-2004 Gerald Brose. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import java.io.*; public class QueryIR { public static void main( String[] args ) { if( args.length != 1 ) { System.err.println("Usage: qir <RepositoryID>"); System.exit(1); } try { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init( args, null ); org.omg.CORBA.Repository ir = org.omg.CORBA.RepositoryHelper.narrow( orb.resolve_initial_references( "InterfaceRepository")); if( ir == null ) { System.out.println( "Could not find IR."); + System.exit(1); } org.omg.CORBA.Contained c = ir.lookup_id( args[0] ); if( c != null ) { IdlWriter idlw = new IdlWriter(System.out); idlw.printContained( c, 2 ); } else System.out.println( args[0] + " not found in IR."); } catch ( Exception e) { e.printStackTrace(); } } }
true
true
public static void main( String[] args ) { if( args.length != 1 ) { System.err.println("Usage: qir <RepositoryID>"); System.exit(1); } try { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init( args, null ); org.omg.CORBA.Repository ir = org.omg.CORBA.RepositoryHelper.narrow( orb.resolve_initial_references( "InterfaceRepository")); if( ir == null ) { System.out.println( "Could not find IR."); } org.omg.CORBA.Contained c = ir.lookup_id( args[0] ); if( c != null ) { IdlWriter idlw = new IdlWriter(System.out); idlw.printContained( c, 2 ); } else System.out.println( args[0] + " not found in IR."); } catch ( Exception e) { e.printStackTrace(); } }
public static void main( String[] args ) { if( args.length != 1 ) { System.err.println("Usage: qir <RepositoryID>"); System.exit(1); } try { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init( args, null ); org.omg.CORBA.Repository ir = org.omg.CORBA.RepositoryHelper.narrow( orb.resolve_initial_references( "InterfaceRepository")); if( ir == null ) { System.out.println( "Could not find IR."); System.exit(1); } org.omg.CORBA.Contained c = ir.lookup_id( args[0] ); if( c != null ) { IdlWriter idlw = new IdlWriter(System.out); idlw.printContained( c, 2 ); } else System.out.println( args[0] + " not found in IR."); } catch ( Exception e) { e.printStackTrace(); } }
diff --git a/common/se/mickelus/modjam/creation/SaveCommand.java b/common/se/mickelus/modjam/creation/SaveCommand.java index 2417629..f765c39 100644 --- a/common/se/mickelus/modjam/creation/SaveCommand.java +++ b/common/se/mickelus/modjam/creation/SaveCommand.java @@ -1,158 +1,158 @@ package se.mickelus.modjam.creation; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.text.html.parser.Entity; import se.mickelus.modjam.Constants; import net.minecraft.client.Minecraft; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.MinecraftForge; public class SaveCommand implements ICommand{ public SaveCommand() { } @Override public int compareTo(Object arg0) { // TODO Auto-generated method stub return 0; } @Override public String getCommandName() { return Constants.SAVE_CMD; } @Override public String getCommandUsage(ICommandSender icommandsender) { return Constants.SAVE_CMD + " <name> <type> <west> <east> <top> <bottom> <south> <north>"; } @Override public List getCommandAliases() { // TODO Auto-generated method stub return null; } @Override public void processCommand(ICommandSender icommandsender, String[] astring) { EntityPlayer player = (EntityPlayer) icommandsender; if(astring.length != 8){ if(icommandsender instanceof EntityPlayer) { player.addChatMessage(getCommandUsage(icommandsender)); } return; } if(icommandsender instanceof EntityPlayer) { File dir = new File(Constants.SAVE_PATH); System.out.println(dir); if(!dir.exists()){ dir.mkdirs(); } File file = MinecraftServer.getServer().getFile(Constants.SAVE_PATH + Constants.SAVE_NAME); System.out.println(file); NBTTagCompound nbt = null; if(!file.exists()){ try { file.createNewFile(); nbt = new NBTTagCompound(); } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream filein = new FileInputStream(file); nbt = CompressedStreamTools.readCompressed(filein); filein.close(); } catch(Exception e) { e.printStackTrace(); } } try { int[] shape = new int[4096]; int x = player.chunkCoordX * 16; int y = player.chunkCoordY * 16; int z = player.chunkCoordZ * 16; - int type = Integer.parseInt(astring[2]); + int type = Integer.parseInt(astring[1]); int west = Integer.parseInt(astring[2]); int east = Integer.parseInt(astring[3]); int top = Integer.parseInt(astring[4]); int bottom = Integer.parseInt(astring[5]); int south = Integer.parseInt(astring[6]); int north = Integer.parseInt(astring[7]); for(int sx = 0; sx < 16; sx++) { for(int sy = 0; sy < 16; sy++) { for(int sz = 0; sz < 16; sz++) { shape[(sx*256+sy*16+sz)] = player.worldObj.getBlockId(x+sx, y+sy, z+sz); } } } NBTTagCompound nbtSegment = new NBTTagCompound(); nbtSegment.setIntArray("blocks", shape); nbtSegment.setInteger("west", west); nbtSegment.setInteger("east", east); nbtSegment.setInteger("top", top); nbtSegment.setInteger("bottom", bottom); nbtSegment.setInteger("south", south); nbtSegment.setInteger("north", north); nbtSegment.setInteger("type", type); nbt.setCompoundTag(astring[0], nbtSegment); FileOutputStream fileos = new FileOutputStream(file); CompressedStreamTools.writeCompressed(nbt, fileos); fileos.close(); } catch(Exception e){ e.printStackTrace(); } } } @Override public boolean canCommandSenderUseCommand(ICommandSender icommandsender) { return true; } @Override public List addTabCompletionOptions(ICommandSender icommandsender, String[] astring) { // TODO Auto-generated method stub return null; } @Override public boolean isUsernameIndex(String[] astring, int i) { // TODO Auto-generated method stub return false; } }
true
true
public void processCommand(ICommandSender icommandsender, String[] astring) { EntityPlayer player = (EntityPlayer) icommandsender; if(astring.length != 8){ if(icommandsender instanceof EntityPlayer) { player.addChatMessage(getCommandUsage(icommandsender)); } return; } if(icommandsender instanceof EntityPlayer) { File dir = new File(Constants.SAVE_PATH); System.out.println(dir); if(!dir.exists()){ dir.mkdirs(); } File file = MinecraftServer.getServer().getFile(Constants.SAVE_PATH + Constants.SAVE_NAME); System.out.println(file); NBTTagCompound nbt = null; if(!file.exists()){ try { file.createNewFile(); nbt = new NBTTagCompound(); } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream filein = new FileInputStream(file); nbt = CompressedStreamTools.readCompressed(filein); filein.close(); } catch(Exception e) { e.printStackTrace(); } } try { int[] shape = new int[4096]; int x = player.chunkCoordX * 16; int y = player.chunkCoordY * 16; int z = player.chunkCoordZ * 16; int type = Integer.parseInt(astring[2]); int west = Integer.parseInt(astring[2]); int east = Integer.parseInt(astring[3]); int top = Integer.parseInt(astring[4]); int bottom = Integer.parseInt(astring[5]); int south = Integer.parseInt(astring[6]); int north = Integer.parseInt(astring[7]); for(int sx = 0; sx < 16; sx++) { for(int sy = 0; sy < 16; sy++) { for(int sz = 0; sz < 16; sz++) { shape[(sx*256+sy*16+sz)] = player.worldObj.getBlockId(x+sx, y+sy, z+sz); } } } NBTTagCompound nbtSegment = new NBTTagCompound(); nbtSegment.setIntArray("blocks", shape); nbtSegment.setInteger("west", west); nbtSegment.setInteger("east", east); nbtSegment.setInteger("top", top); nbtSegment.setInteger("bottom", bottom); nbtSegment.setInteger("south", south); nbtSegment.setInteger("north", north); nbtSegment.setInteger("type", type); nbt.setCompoundTag(astring[0], nbtSegment); FileOutputStream fileos = new FileOutputStream(file); CompressedStreamTools.writeCompressed(nbt, fileos); fileos.close(); } catch(Exception e){ e.printStackTrace(); } } }
public void processCommand(ICommandSender icommandsender, String[] astring) { EntityPlayer player = (EntityPlayer) icommandsender; if(astring.length != 8){ if(icommandsender instanceof EntityPlayer) { player.addChatMessage(getCommandUsage(icommandsender)); } return; } if(icommandsender instanceof EntityPlayer) { File dir = new File(Constants.SAVE_PATH); System.out.println(dir); if(!dir.exists()){ dir.mkdirs(); } File file = MinecraftServer.getServer().getFile(Constants.SAVE_PATH + Constants.SAVE_NAME); System.out.println(file); NBTTagCompound nbt = null; if(!file.exists()){ try { file.createNewFile(); nbt = new NBTTagCompound(); } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream filein = new FileInputStream(file); nbt = CompressedStreamTools.readCompressed(filein); filein.close(); } catch(Exception e) { e.printStackTrace(); } } try { int[] shape = new int[4096]; int x = player.chunkCoordX * 16; int y = player.chunkCoordY * 16; int z = player.chunkCoordZ * 16; int type = Integer.parseInt(astring[1]); int west = Integer.parseInt(astring[2]); int east = Integer.parseInt(astring[3]); int top = Integer.parseInt(astring[4]); int bottom = Integer.parseInt(astring[5]); int south = Integer.parseInt(astring[6]); int north = Integer.parseInt(astring[7]); for(int sx = 0; sx < 16; sx++) { for(int sy = 0; sy < 16; sy++) { for(int sz = 0; sz < 16; sz++) { shape[(sx*256+sy*16+sz)] = player.worldObj.getBlockId(x+sx, y+sy, z+sz); } } } NBTTagCompound nbtSegment = new NBTTagCompound(); nbtSegment.setIntArray("blocks", shape); nbtSegment.setInteger("west", west); nbtSegment.setInteger("east", east); nbtSegment.setInteger("top", top); nbtSegment.setInteger("bottom", bottom); nbtSegment.setInteger("south", south); nbtSegment.setInteger("north", north); nbtSegment.setInteger("type", type); nbt.setCompoundTag(astring[0], nbtSegment); FileOutputStream fileos = new FileOutputStream(file); CompressedStreamTools.writeCompressed(nbt, fileos); fileos.close(); } catch(Exception e){ e.printStackTrace(); } } }
diff --git a/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java b/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java index 5c954a64d..f9584e5d8 100644 --- a/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java +++ b/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java @@ -1,301 +1,303 @@ /* * ItemListTag.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2001, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.webui.jsptag; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.LinkedList; import javax.servlet.ServletException; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.http.HttpServletRequest; import org.dspace.app.webui.util.UIUtil; import org.dspace.content.DCDate; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.handle.HandleManager; /** * Tag for display a list of items * * @author Robert Tansley * @version $Revision$ */ public class ItemListTag extends TagSupport { /** Items to display */ private Item[] items; /** Corresponding handles */ private String[] handles; /** Row to highlight, -1 for no row */ private int highlightRow; /** Column to emphasise - null, "title" or "date" */ private String emphColumn; public ItemListTag() { super(); } public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } try { out.println("<table align=center class=\"miscTable\">"); // Row: toggles between Odd and Even String row = "odd"; for (int i = 0; i < items.length; i++) { // Title - we just use the first one DCValue[] titleArray = items[i].getDC("title", null, Item.ANY); String title = "Untitled"; if (titleArray.length > 0) { title = titleArray[0].value; } // Authors.... DCValue[] authors = items[i].getDC("contributor", "author", Item.ANY); // Date issued DCValue[] dateIssued = items[i].getDC("date", "issued", Item.ANY); DCDate dd = null; if(dateIssued.length > 0) { dd = new DCDate(dateIssued[0].value); } // First column is date out.print("<tr><td nowrap class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowOddCol\" align=right>"); if (emphasiseDate) { out.print("<strong>"); } out.print(UIUtil.displayDate(dd, false, false)); if (emphasiseDate) { out.print("</strong>"); } // Second column is title out.print("</td><td class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowEvenCol\">"); if (emphasiseTitle) { out.print("<strong>"); } out.print("<A HREF=\"item/"); out.print(handles[i]); out.print("\">"); out.print(title); out.print("</A>"); if (emphasiseTitle) { out.print("</strong>"); } // Third column is authors - out.print("</td><td class=\"" + row + "RowOddCol\">"); + out.print("</td><td class=\""); + out.print(i == highlightRow ? "highlight" : row); + out.print("RowOddCol\">"); for (int j = 0; j < authors.length; j++) { out.print("<em>" + authors[j].value + "</em>"); if (j < authors.length - 1) { out.print("; "); } } out.println("</td></tr>"); row = (row.equals("odd") ? "even" : "odd"); } out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } return SKIP_BODY; } /** * Get the items to list * * @return the items */ public List getItems() { return Arrays.asList(items); } /** * Set the items to list * * @param itemsIn the items */ public void setItems(List itemsIn) { items = new Item[itemsIn.size()]; items = (Item[]) itemsIn.toArray(items); } /** * Get the corresponding handles * * @return the handles */ public String[] getHandles() { return handles; } /** * Set the handles corresponding to items * * @param handlesIn the handles */ public void setHandles(String[] handlesIn) { handles = handlesIn; } /** * Get the row to highlight - null or -1 for no row * * @return the row to highlight */ public String getHighlightrow() { return String.valueOf(highlightRow); } /** * Set the row to highlight * * @param highlightRowIn the row to highlight or -1 for no highlight */ public void setHighlightrow(String highlightRowIn) { if (highlightRowIn == null) { highlightRow = -1; } else { try { highlightRow = Integer.parseInt(highlightRowIn); } catch(NumberFormatException nfe) { highlightRow = -1; } } } /** * Get the column to emphasise - "title", "date" or null * * @return the column to emphasise */ public String getEmphcolumn() { return emphColumn; } /** * Set the column to emphasise - "title", "date" or null * * @param emphcolumnIn column to emphasise */ public void setEmphcolumn(String emphColumnIn) { emphColumn = emphColumnIn; } }
true
true
public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } try { out.println("<table align=center class=\"miscTable\">"); // Row: toggles between Odd and Even String row = "odd"; for (int i = 0; i < items.length; i++) { // Title - we just use the first one DCValue[] titleArray = items[i].getDC("title", null, Item.ANY); String title = "Untitled"; if (titleArray.length > 0) { title = titleArray[0].value; } // Authors.... DCValue[] authors = items[i].getDC("contributor", "author", Item.ANY); // Date issued DCValue[] dateIssued = items[i].getDC("date", "issued", Item.ANY); DCDate dd = null; if(dateIssued.length > 0) { dd = new DCDate(dateIssued[0].value); } // First column is date out.print("<tr><td nowrap class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowOddCol\" align=right>"); if (emphasiseDate) { out.print("<strong>"); } out.print(UIUtil.displayDate(dd, false, false)); if (emphasiseDate) { out.print("</strong>"); } // Second column is title out.print("</td><td class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowEvenCol\">"); if (emphasiseTitle) { out.print("<strong>"); } out.print("<A HREF=\"item/"); out.print(handles[i]); out.print("\">"); out.print(title); out.print("</A>"); if (emphasiseTitle) { out.print("</strong>"); } // Third column is authors out.print("</td><td class=\"" + row + "RowOddCol\">"); for (int j = 0; j < authors.length; j++) { out.print("<em>" + authors[j].value + "</em>"); if (j < authors.length - 1) { out.print("; "); } } out.println("</td></tr>"); row = (row.equals("odd") ? "even" : "odd"); } out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } return SKIP_BODY; }
public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } try { out.println("<table align=center class=\"miscTable\">"); // Row: toggles between Odd and Even String row = "odd"; for (int i = 0; i < items.length; i++) { // Title - we just use the first one DCValue[] titleArray = items[i].getDC("title", null, Item.ANY); String title = "Untitled"; if (titleArray.length > 0) { title = titleArray[0].value; } // Authors.... DCValue[] authors = items[i].getDC("contributor", "author", Item.ANY); // Date issued DCValue[] dateIssued = items[i].getDC("date", "issued", Item.ANY); DCDate dd = null; if(dateIssued.length > 0) { dd = new DCDate(dateIssued[0].value); } // First column is date out.print("<tr><td nowrap class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowOddCol\" align=right>"); if (emphasiseDate) { out.print("<strong>"); } out.print(UIUtil.displayDate(dd, false, false)); if (emphasiseDate) { out.print("</strong>"); } // Second column is title out.print("</td><td class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowEvenCol\">"); if (emphasiseTitle) { out.print("<strong>"); } out.print("<A HREF=\"item/"); out.print(handles[i]); out.print("\">"); out.print(title); out.print("</A>"); if (emphasiseTitle) { out.print("</strong>"); } // Third column is authors out.print("</td><td class=\""); out.print(i == highlightRow ? "highlight" : row); out.print("RowOddCol\">"); for (int j = 0; j < authors.length; j++) { out.print("<em>" + authors[j].value + "</em>"); if (j < authors.length - 1) { out.print("; "); } } out.println("</td></tr>"); row = (row.equals("odd") ? "even" : "odd"); } out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } return SKIP_BODY; }
diff --git a/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java b/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java index 8bb536b..f16b481 100644 --- a/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java +++ b/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java @@ -1,470 +1,470 @@ package net.croxis.plugins.civilmineation; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.PersistenceException; import net.croxis.plugins.civilmineation.components.CityComponent; import net.croxis.plugins.civilmineation.components.CivilizationComponent; import net.croxis.plugins.civilmineation.components.Component; import net.croxis.plugins.civilmineation.components.EconomyComponent; import net.croxis.plugins.civilmineation.components.Ent; import net.croxis.plugins.civilmineation.components.PermissionComponent; import net.croxis.plugins.civilmineation.components.PlotComponent; import net.croxis.plugins.civilmineation.components.ResidentComponent; import net.croxis.plugins.research.Tech; import net.croxis.plugins.research.TechManager; import org.bukkit.ChatColor; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import net.milkbowl.vault.economy.Economy; public class Civilmineation extends JavaPlugin implements Listener { public static CivAPI api; private static final Logger logger = Logger.getLogger("Minecraft"); public static void log(String message){ logger.info("[Civ] " + message); } public static void log(Level level, String message){ logger.info("[Civ] " + message); } public static void logDebug(String message){ logger.info("[Civ][Debug] " + message); } public void onDisable() { // TODO: Place any custom disable code here. } private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } CivAPI.econ = rsp.getProvider(); return CivAPI.econ != null; } public void onEnable() { setupDatabase(); api = new CivAPI(this); if (!setupEconomy() ) { log(Level.SEVERE, "Disabled due to no Vault dependency found!"); getServer().getPluginManager().disablePlugin(this); return; } getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(new ActionPermissionListener(), this); getServer().getPluginManager().registerEvents(new SignInteractListener(), this); getCommand("tech").setExecutor(new TechCommand(this)); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run(){ logDebug("Running Turn"); for (Player player : getServer().getOnlinePlayers()){ ResidentComponent resident = CivAPI.getResident(player); if (resident.getCity() != null){ CivAPI.addCulture(resident.getCity(), 1); CivAPI.addResearch(resident.getCity(), 1); } else { Tech learned = TechManager.addPoints(player, 1); if(learned != null) player.sendMessage("You have learned a technology!"); } } } }, 36000, 36000); } public Ent createEntity(){ Ent ent = new Ent(); getDatabase().save(ent); return ent; } public Ent createEntity(String name){ Ent ent = new Ent(); ent.setDebugName(name); getDatabase().save(ent); return ent; } public void addComponent(Ent ent, Component component){ component.setEntityID(ent); getDatabase().save(component); return; } @Override public List<Class<?>> getDatabaseClasses() { List<Class<?>> list = new ArrayList<Class<?>>(); list.add(Ent.class); list.add(ResidentComponent.class); list.add(CityComponent.class); list.add(CivilizationComponent.class); list.add(PlotComponent.class); list.add(PermissionComponent.class); list.add(EconomyComponent.class); return list; } private void setupDatabase() { try { getDatabase().find(Ent.class).findRowCount(); } catch(PersistenceException ex) { System.out.println("Installing database for " + getDescription().getName() + " due to first time usage"); installDDL(); } //Ent ent = createEntity(); //CivilizationComponent wilderness = new CivilizationComponent(); //wilderness.setName("Wilderness"); //addComponent(ent, wilderness); } @EventHandler public void onSignChangeEvent(SignChangeEvent event){ if (event.getLine(0).equalsIgnoreCase("[New Civ]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName()); if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("Civ name on second line, Capital name on third line"); event.setCancelled(true); return; } CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique(); CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (civComponent != null || cityComponent != null){ event.getPlayer().sendMessage("That civ or city name already exists"); event.setCancelled(true); return; } if (resident.getCity() != null){ event.getPlayer().sendMessage("You must leave your city first."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } //TODO: Distance check to another city //TODO: Check for room for interface placements Ent civEntity = createEntity("Civ " + event.getLine(1)); CivilizationComponent civ = new CivilizationComponent(); civ.setName(event.getLine(1)); //addComponent(civEntity, civ); civ.setEntityID(civEntity); civ.setRegistered(System.currentTimeMillis()); civ.setTaxes(0); getDatabase().save(civ); EconomyComponent civEcon = new EconomyComponent(); civEcon.setName(event.getLine(1)); civEcon.setEntityID(civEntity); getDatabase().save(civEcon); CivAPI.econ.createPlayerAccount(event.getLine(1)); PermissionComponent civPerm = new PermissionComponent(); civPerm.setAll(false); civPerm.setResidentBuild(true); civPerm.setResidentDestroy(true); civPerm.setResidentItemUse(true); civPerm.setResidentSwitch(true); civPerm.setName(event.getLine(1) + " permissions"); //addComponent(civEntity, civPerm); civPerm.setEntityID(civEntity); getDatabase().save(civPerm); ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); - CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), true); + CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), civ, true); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true); Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState(); plotSign.setLine(0, city.getName()); plotSign.update(); plot.setSignX(plotSign.getX()); plot.setSignY(plotSign.getY()); plot.setSignZ(plotSign.getZ()); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(3, "Mayor " + event.getPlayer().getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[claim]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (resident.getCity() == null){ event.setCancelled(true); event.getPlayer().sendMessage("You must be part of a city admin"); return; } else if (!resident.isCityAssistant() && !resident.isMayor()){ event.setCancelled(true); event.getPlayer().sendMessage("You must be a city admin"); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.setCancelled(true); event.getPlayer().sendMessage("A city has already claimed this chunk"); return; } } else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){ event.setCancelled(true); event.getPlayer().sendMessage("You do not have enough culture"); return; } //CivAPI.addCulture(resident.getCity(), (int) -(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5))); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(resident.getCity()); plot.setName(resident.getCity().getName()); plot.setSignX(event.getBlock().getX()); plot.setSignY(event.getBlock().getY()); plot.setSignZ(event.getBlock().getZ()); getDatabase().save(plot); event.setLine(0, resident.getCity().getName()); } else if (event.getLine(0).equalsIgnoreCase("[new city]")){ if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("City name on second line, Mayor name on third line"); event.setCancelled(true); return; } ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (!CivAPI.isNationalAdmin(resident)){ event.getPlayer().sendMessage("You must be a national leader or assistant."); event.setCancelled(true); return; } ResidentComponent mayor = CivAPI.getResident(event.getLine(2)); if (mayor == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (cityComponent != null){ event.getPlayer().sendMessage("That city name already exists"); event.setCancelled(true); return; } if (mayor.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (mayor.isMayor()){ event.getPlayer().sendMessage("That player can not be am existing mayor."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(1, city.getCivilization().getName()); event.setLine(2, city.getName()); event.setLine(3, "Mayor " + mayor.getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){ ResidentComponent king = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!CivAPI.isKing(king)){ event.getPlayer().sendMessage("You must be a king."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } assistant.setCivAssistant(!assistant.isCivAssistant()); getDatabase().save(assistant); if(assistant.isCivAssistant()) CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization()); else CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization()); return; } else if (event.getLine(0).equalsIgnoreCase("[city assist]")){ ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!mayor.isMayor()){ event.getPlayer().sendMessage("You must be a mayor."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } assistant.setCityAssistant(!assistant.isCityAssistant()); getDatabase().save(assistant); if(assistant.isCityAssistant()) CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity()); else CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity()); return; } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (resident == null){ Ent entity = createEntity(); EconomyComponent civEcon = new EconomyComponent(); civEcon.setName(event.getPlayer().getName()); civEcon.setEntityID(entity); getDatabase().save(civEcon); resident = new ResidentComponent(); resident.setRegistered(System.currentTimeMillis()); resident.setName(event.getPlayer().getName()); //addComponent(entity, resident); resident.setEntityID(entity); getDatabase().save(resident); } String title = ""; if (resident.isMayor()){ title = "Mayor "; if (resident.getCity().isCapital()) title = "King "; } else if (resident.getCity() == null) title = "Wild "; event.getPlayer().sendMessage("Welcome, " + title + event.getPlayer().getDisplayName() + "!"); } @EventHandler public void onPlayerMove(PlayerMoveEvent event){ if (event.getFrom().getWorld().getChunkAt(event.getFrom()).getX() != event.getTo().getWorld().getChunkAt(event.getTo()).getX() || event.getFrom().getWorld().getChunkAt(event.getFrom()).getZ() != event.getTo().getWorld().getChunkAt(event.getTo()).getZ()){ //event.getPlayer().sendMessage("Message will go here"); PlotComponent plot = CivAPI.getPlot(event.getTo().getChunk()); PlotComponent plotFrom = CivAPI.getPlot(event.getFrom().getChunk()); if (plot == null && plotFrom != null){ event.getPlayer().sendMessage("Wilds"); } else if (plot == null && plotFrom == null){ // Needed to prevent future NPES } else if (plot != null && plotFrom == null){ // TODO: City enter event event.getPlayer().sendMessage(plot.getName()); } else if (!plot.getName().equalsIgnoreCase(plotFrom.getName())){ event.getPlayer().sendMessage(plot.getName()); } } } }
true
true
public void onSignChangeEvent(SignChangeEvent event){ if (event.getLine(0).equalsIgnoreCase("[New Civ]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName()); if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("Civ name on second line, Capital name on third line"); event.setCancelled(true); return; } CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique(); CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (civComponent != null || cityComponent != null){ event.getPlayer().sendMessage("That civ or city name already exists"); event.setCancelled(true); return; } if (resident.getCity() != null){ event.getPlayer().sendMessage("You must leave your city first."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } //TODO: Distance check to another city //TODO: Check for room for interface placements Ent civEntity = createEntity("Civ " + event.getLine(1)); CivilizationComponent civ = new CivilizationComponent(); civ.setName(event.getLine(1)); //addComponent(civEntity, civ); civ.setEntityID(civEntity); civ.setRegistered(System.currentTimeMillis()); civ.setTaxes(0); getDatabase().save(civ); EconomyComponent civEcon = new EconomyComponent(); civEcon.setName(event.getLine(1)); civEcon.setEntityID(civEntity); getDatabase().save(civEcon); CivAPI.econ.createPlayerAccount(event.getLine(1)); PermissionComponent civPerm = new PermissionComponent(); civPerm.setAll(false); civPerm.setResidentBuild(true); civPerm.setResidentDestroy(true); civPerm.setResidentItemUse(true); civPerm.setResidentSwitch(true); civPerm.setName(event.getLine(1) + " permissions"); //addComponent(civEntity, civPerm); civPerm.setEntityID(civEntity); getDatabase().save(civPerm); ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), true); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true); Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState(); plotSign.setLine(0, city.getName()); plotSign.update(); plot.setSignX(plotSign.getX()); plot.setSignY(plotSign.getY()); plot.setSignZ(plotSign.getZ()); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(3, "Mayor " + event.getPlayer().getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[claim]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (resident.getCity() == null){ event.setCancelled(true); event.getPlayer().sendMessage("You must be part of a city admin"); return; } else if (!resident.isCityAssistant() && !resident.isMayor()){ event.setCancelled(true); event.getPlayer().sendMessage("You must be a city admin"); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.setCancelled(true); event.getPlayer().sendMessage("A city has already claimed this chunk"); return; } } else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){ event.setCancelled(true); event.getPlayer().sendMessage("You do not have enough culture"); return; } //CivAPI.addCulture(resident.getCity(), (int) -(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5))); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(resident.getCity()); plot.setName(resident.getCity().getName()); plot.setSignX(event.getBlock().getX()); plot.setSignY(event.getBlock().getY()); plot.setSignZ(event.getBlock().getZ()); getDatabase().save(plot); event.setLine(0, resident.getCity().getName()); } else if (event.getLine(0).equalsIgnoreCase("[new city]")){ if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("City name on second line, Mayor name on third line"); event.setCancelled(true); return; } ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (!CivAPI.isNationalAdmin(resident)){ event.getPlayer().sendMessage("You must be a national leader or assistant."); event.setCancelled(true); return; } ResidentComponent mayor = CivAPI.getResident(event.getLine(2)); if (mayor == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (cityComponent != null){ event.getPlayer().sendMessage("That city name already exists"); event.setCancelled(true); return; } if (mayor.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (mayor.isMayor()){ event.getPlayer().sendMessage("That player can not be am existing mayor."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(1, city.getCivilization().getName()); event.setLine(2, city.getName()); event.setLine(3, "Mayor " + mayor.getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){ ResidentComponent king = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!CivAPI.isKing(king)){ event.getPlayer().sendMessage("You must be a king."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } assistant.setCivAssistant(!assistant.isCivAssistant()); getDatabase().save(assistant); if(assistant.isCivAssistant()) CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization()); else CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization()); return; } else if (event.getLine(0).equalsIgnoreCase("[city assist]")){ ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!mayor.isMayor()){ event.getPlayer().sendMessage("You must be a mayor."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } assistant.setCityAssistant(!assistant.isCityAssistant()); getDatabase().save(assistant); if(assistant.isCityAssistant()) CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity()); else CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity()); return; } }
public void onSignChangeEvent(SignChangeEvent event){ if (event.getLine(0).equalsIgnoreCase("[New Civ]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName()); if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("Civ name on second line, Capital name on third line"); event.setCancelled(true); return; } CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique(); CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (civComponent != null || cityComponent != null){ event.getPlayer().sendMessage("That civ or city name already exists"); event.setCancelled(true); return; } if (resident.getCity() != null){ event.getPlayer().sendMessage("You must leave your city first."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } //TODO: Distance check to another city //TODO: Check for room for interface placements Ent civEntity = createEntity("Civ " + event.getLine(1)); CivilizationComponent civ = new CivilizationComponent(); civ.setName(event.getLine(1)); //addComponent(civEntity, civ); civ.setEntityID(civEntity); civ.setRegistered(System.currentTimeMillis()); civ.setTaxes(0); getDatabase().save(civ); EconomyComponent civEcon = new EconomyComponent(); civEcon.setName(event.getLine(1)); civEcon.setEntityID(civEntity); getDatabase().save(civEcon); CivAPI.econ.createPlayerAccount(event.getLine(1)); PermissionComponent civPerm = new PermissionComponent(); civPerm.setAll(false); civPerm.setResidentBuild(true); civPerm.setResidentDestroy(true); civPerm.setResidentItemUse(true); civPerm.setResidentSwitch(true); civPerm.setName(event.getLine(1) + " permissions"); //addComponent(civEntity, civPerm); civPerm.setEntityID(civEntity); getDatabase().save(civPerm); ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), civ, true); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true); Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState(); plotSign.setLine(0, city.getName()); plotSign.update(); plot.setSignX(plotSign.getX()); plot.setSignY(plotSign.getY()); plot.setSignZ(plotSign.getZ()); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(3, "Mayor " + event.getPlayer().getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[claim]")){ ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (resident.getCity() == null){ event.setCancelled(true); event.getPlayer().sendMessage("You must be part of a city admin"); return; } else if (!resident.isCityAssistant() && !resident.isMayor()){ event.setCancelled(true); event.getPlayer().sendMessage("You must be a city admin"); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.setCancelled(true); event.getPlayer().sendMessage("A city has already claimed this chunk"); return; } } else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){ event.setCancelled(true); event.getPlayer().sendMessage("You do not have enough culture"); return; } //CivAPI.addCulture(resident.getCity(), (int) -(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5))); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(resident.getCity()); plot.setName(resident.getCity().getName()); plot.setSignX(event.getBlock().getX()); plot.setSignY(event.getBlock().getY()); plot.setSignZ(event.getBlock().getZ()); getDatabase().save(plot); event.setLine(0, resident.getCity().getName()); } else if (event.getLine(0).equalsIgnoreCase("[new city]")){ if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){ event.getPlayer().sendMessage("City name on second line, Mayor name on third line"); event.setCancelled(true); return; } ResidentComponent resident = CivAPI.getResident(event.getPlayer()); if (!CivAPI.isNationalAdmin(resident)){ event.getPlayer().sendMessage("You must be a national leader or assistant."); event.setCancelled(true); return; } ResidentComponent mayor = CivAPI.getResident(event.getLine(2)); if (mayor == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique(); if (cityComponent != null){ event.getPlayer().sendMessage("That city name already exists"); event.setCancelled(true); return; } if (mayor.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (mayor.isMayor()){ event.getPlayer().sendMessage("That player can not be am existing mayor."); event.setCancelled(true); return; } PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk()); if (plot != null){ if (plot.getCity() != null){ event.getPlayer().sendMessage("That plot is part of a city."); event.setCancelled(true); return; } } CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false); if (plot == null){ Ent plotEnt = createEntity(); plot = new PlotComponent(); plot.setX(event.getBlock().getChunk().getX()); plot.setZ(event.getBlock().getChunk().getZ()); //addComponent(plotEnt, plot); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(city.getName() + " Founding Square"); getDatabase().save(plot); event.setLine(0, ChatColor.BLUE + "City Charter"); event.setLine(1, city.getCivilization().getName()); event.setLine(2, city.getName()); event.setLine(3, "Mayor " + mayor.getName()); event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true); //event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true); CivAPI.updateCityCharter(city); } else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){ ResidentComponent king = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!CivAPI.isKing(king)){ event.getPlayer().sendMessage("You must be a king."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){ event.getPlayer().sendMessage("That player must be in your civ!."); event.setCancelled(true); return; } assistant.setCivAssistant(!assistant.isCivAssistant()); getDatabase().save(assistant); if(assistant.isCivAssistant()) CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization()); else CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization()); return; } else if (event.getLine(0).equalsIgnoreCase("[city assist]")){ ResidentComponent mayor = CivAPI.getResident(event.getPlayer()); event.getBlock().breakNaturally(); if (event.getLine(1).isEmpty()){ event.getPlayer().sendMessage("Assistant name on the second line."); event.setCancelled(true); return; } else if (!mayor.isMayor()){ event.getPlayer().sendMessage("You must be a mayor."); event.setCancelled(true); return; } ResidentComponent assistant = CivAPI.getResident(event.getLine(1)); if (assistant == null){ event.getPlayer().sendMessage("That player does not exist."); event.setCancelled(true); return; } if (assistant.getCity() == null){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){ event.getPlayer().sendMessage("That player must be in your city!."); event.setCancelled(true); return; } assistant.setCityAssistant(!assistant.isCityAssistant()); getDatabase().save(assistant); if(assistant.isCityAssistant()) CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity()); else CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity()); return; } }
diff --git a/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/Line.java b/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/Line.java index f38d829b..5bfffea1 100644 --- a/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/Line.java +++ b/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/Line.java @@ -1,163 +1,163 @@ package dk.itu.big_red.model.assistants; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; /** * Lines represent line segments. * @author alec * */ public class Line { private Point p1 = new Point(), p2 = new Point(); private Rectangle bounds = new Rectangle(); /** * Constructs a line from <code>(0, 0)</code> to <code>(0, 0)</code>. */ public Line() { } /** * Constructs a line between the two points given. * @param p1 the first point * @param p2 the second point */ public Line(Point p1, Point p2) { setFirstPoint(p1); setSecondPoint(p2); } /** * Gets the first point on this line. * @return the first point */ public Point getFirstPoint() { return p1; } /** * Overwrites the first point on this line with <code>p</code>. * @param p a Point */ public void setFirstPoint(Point p) { if (p != null) p1.setLocation(p); } /** * Gets the second point on this line. * @param p the second point */ public Point getSecondPoint() { return p1; } /** * Overwrites the second point on this line with <code>p</code>. * @param p a Point */ public void setSecondPoint(Point p) { if (p != null) p2.setLocation(p); } /** * Returns the gradient of this line. * @return a gradient */ public double getGradient() { return (p2.y - p1.y) / (double)(p2.x - p1.x); } /** * Returns the gradient of the line perpendicular to this one. * @return a gradient */ public double getPerpendicularGradient() { return -1 / getGradient(); } /** * Returns the point where this line and the line perpendicular to it which * passes through point <code>p3</code> meet. * @param p3 a Point * @return the point of intersection, or <code>null</code> if there isn't * one */ public Point getIntersection(Point p3) { return getIntersection(new Point(), p3); } /** * As {@link #getIntersection(Point)}, but doesn't allocate a new point. * @param target the Point to store the result in * @param p3 a Point * @return the point of intersection, or <code>null</code> if there isn't * one */ public Point getIntersection(Point target, Point p3) { if (p3.equals(p1)) { return target.setLocation(p1); } else if (p3.equals(p2)) { return target.setLocation(p2); } else if (p1.x == p2.x) { target.setLocation(p1.x, p3.y); } else if (p1.y == p2.y){ target.setLocation(p3.x, p1.y); } else { double m_ = getGradient(), m = getPerpendicularGradient(); double x = ((m_ * p1.x) - p1.y - (m * p3.x) + p3.y) / (m_ - m), y = m_ * (x - p1.x) + p1.y; target.setLocation((int)Math.round(x), (int)Math.round(y)); } - bounds.setBounds(p1.x, p2.y, 0, 0).union(p2); + bounds.setBounds(p1.x, p1.y, 0, 0).union(p2); return (bounds.contains(target) ? target : null); } /** * Returns the point at a given offset along the line (where * <code>p1</code> is <code>0.0</code> and <code>p2</code> is * <code>1.0</code>). * @param offset an offset between <code>0</code> and <code>1</code> * inclusive * @return a Point on this line segment, or <code>null</code> if * <code>offset</code> is out of bounds */ public Point getPointFromOffset(double offset) { if (offset >= 0.0 && offset <= 1.0) return p1.getCopy().translate(p2.getDifference(p1).scale(offset)); else return null; } /** * Returns the offset of a given point along the line (where * <code>p1</code> is <code>0.0</code> and <code>p2</code> is * <code>1.0</code>). * @param point a Point on this line segment * @return an offset on this line segment, or {@link Double#NaN} if * <code>point</code> isn't on this line */ public double getOffsetFromPoint(Point point) { if (getIntersection(point).equals(point)) { Dimension dp = p1.getDifference(point), dt = p1.getDifference(p2); double d1 = (double)dp.width / dt.width, d2 = (double)dp.height / dt.height; if (Double.isNaN(d1)) return d2; else return d1; } else return Double.NaN; } /** * Returns the length of this line (i.e., the Euclidean distance between * its two points). */ public double getLength() { return p1.getDistance(p2); } }
true
true
public Point getIntersection(Point target, Point p3) { if (p3.equals(p1)) { return target.setLocation(p1); } else if (p3.equals(p2)) { return target.setLocation(p2); } else if (p1.x == p2.x) { target.setLocation(p1.x, p3.y); } else if (p1.y == p2.y){ target.setLocation(p3.x, p1.y); } else { double m_ = getGradient(), m = getPerpendicularGradient(); double x = ((m_ * p1.x) - p1.y - (m * p3.x) + p3.y) / (m_ - m), y = m_ * (x - p1.x) + p1.y; target.setLocation((int)Math.round(x), (int)Math.round(y)); } bounds.setBounds(p1.x, p2.y, 0, 0).union(p2); return (bounds.contains(target) ? target : null); }
public Point getIntersection(Point target, Point p3) { if (p3.equals(p1)) { return target.setLocation(p1); } else if (p3.equals(p2)) { return target.setLocation(p2); } else if (p1.x == p2.x) { target.setLocation(p1.x, p3.y); } else if (p1.y == p2.y){ target.setLocation(p3.x, p1.y); } else { double m_ = getGradient(), m = getPerpendicularGradient(); double x = ((m_ * p1.x) - p1.y - (m * p3.x) + p3.y) / (m_ - m), y = m_ * (x - p1.x) + p1.y; target.setLocation((int)Math.round(x), (int)Math.round(y)); } bounds.setBounds(p1.x, p1.y, 0, 0).union(p2); return (bounds.contains(target) ? target : null); }
diff --git a/browser/org/eclipse/cdt/core/browser/AllTypesCache.java b/browser/org/eclipse/cdt/core/browser/AllTypesCache.java index a0b2c3905..d66340a51 100644 --- a/browser/org/eclipse/cdt/core/browser/AllTypesCache.java +++ b/browser/org/eclipse/cdt/core/browser/AllTypesCache.java @@ -1,159 +1,160 @@ /******************************************************************************* * Copyright (c) 2004, 2009 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - initial API and implementation * Andrew Ferguson (Symbian) * Markus Schorn (Wind River Systems) *******************************************************************************/ package org.eclipse.cdt.core.browser; import java.util.regex.Pattern; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.index.IIndexBinding; import org.eclipse.cdt.core.index.IndexFilter; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.internal.core.browser.IndexModelUtil; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; /** * Manages a search cache for types in the workspace. Instead of returning * objects of type <code>ICElement</code> the methods of this class returns a * list of the lightweight objects <code>ITypeInfo</code>. * <P> * AllTypesCache runs asynchronously using a background job to rebuild the cache * as needed. If the cache becomes dirty again while the background job is * running, the job is restarted. * <P> * If <code>getTypes</code> is called in response to a user action, a progress * dialog is shown. If called before the background job has finished, getTypes * waits for the completion of the background job. * * @noextend This class is not intended to be subclassed by clients. * @noinstantiate This class is not intended to be instantiated by clients. */ public class AllTypesCache { private static final boolean DEBUG = false; private static ITypeInfo[] getTypes(ICProject[] projects, final int[] kinds, IProgressMonitor monitor) throws CoreException { IIndex index = CCorePlugin.getIndexManager().getIndex(projects); try { index.acquireReadLock(); long start = System.currentTimeMillis(); IIndexBinding[] all = index.findBindings(Pattern.compile(".*"), false, new IndexFilter() { //$NON-NLS-1$ @Override - public boolean acceptBinding(IBinding binding) { - return IndexModelUtil.bindingHasCElementType(binding, kinds); + public boolean acceptBinding(IBinding binding) throws CoreException { + return IndexFilter.ALL_DECLARED_OR_IMPLICIT.acceptBinding(binding) && + IndexModelUtil.bindingHasCElementType(binding, kinds); }}, monitor ); if(DEBUG) { System.out.println("Index search took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } ITypeInfo[] result = new ITypeInfo[all.length]; for(int i=0; i<all.length; i++) { result[i] = IndexTypeInfo.create(index, all[i]); } if(DEBUG) { System.out.println("Wrapping as ITypeInfo took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } return result; } catch(InterruptedException ie) { ie.printStackTrace(); } finally { index.releaseReadLock(); } return new ITypeInfo[0]; } /** * Returns all types in the workspace. */ public static ITypeInfo[] getAllTypes() { return getAllTypes(new NullProgressMonitor()); } /** * Returns all types in the workspace. */ public static ITypeInfo[] getAllTypes(IProgressMonitor monitor) { try { ICProject[] projects = CoreModel.getDefault().getCModel().getCProjects(); return getTypes(projects, ITypeInfo.KNOWN_TYPES, monitor); } catch (CoreException e) { CCorePlugin.log(e); return new ITypeInfo[0]; } } /** * Returns all types in the given scope. * * @param scope The search scope * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, * C_UNION, C_ENUMERATION, C_TYPEDEF */ public static ITypeInfo[] getTypes(ITypeSearchScope scope, int[] kinds) { try { return getTypes(scope.getEnclosingProjects(), kinds, new NullProgressMonitor()); } catch (CoreException e) { CCorePlugin.log(e); return new ITypeInfo[0]; } } /** * Returns all namespaces in the given scope. * * @param scope The search scope * @param includeGlobalNamespace <code>true</code> if the global (default) namespace should be returned */ public static ITypeInfo[] getNamespaces(ITypeSearchScope scope, boolean includeGlobalNamespace) { try { return getTypes(scope.getEnclosingProjects(), new int[] {ICElement.C_NAMESPACE}, new NullProgressMonitor()); } catch (CoreException e) { CCorePlugin.log(e); return new ITypeInfo[0]; } } /** * @noreference This method is not intended to be referenced by clients. * @deprecated never worked. */ @Deprecated public static ITypeInfo getType(ICProject project, int type, IQualifiedTypeName qualifiedName) { return null; } /** * @noreference This method is not intended to be referenced by clients. * @deprecated never worked. */ @Deprecated public static ITypeInfo[] getTypes(ICProject project, IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase) { return new ITypeInfo[0]; } }
true
true
private static ITypeInfo[] getTypes(ICProject[] projects, final int[] kinds, IProgressMonitor monitor) throws CoreException { IIndex index = CCorePlugin.getIndexManager().getIndex(projects); try { index.acquireReadLock(); long start = System.currentTimeMillis(); IIndexBinding[] all = index.findBindings(Pattern.compile(".*"), false, new IndexFilter() { //$NON-NLS-1$ @Override public boolean acceptBinding(IBinding binding) { return IndexModelUtil.bindingHasCElementType(binding, kinds); }}, monitor ); if(DEBUG) { System.out.println("Index search took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } ITypeInfo[] result = new ITypeInfo[all.length]; for(int i=0; i<all.length; i++) { result[i] = IndexTypeInfo.create(index, all[i]); } if(DEBUG) { System.out.println("Wrapping as ITypeInfo took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } return result; } catch(InterruptedException ie) { ie.printStackTrace(); } finally { index.releaseReadLock(); } return new ITypeInfo[0]; }
private static ITypeInfo[] getTypes(ICProject[] projects, final int[] kinds, IProgressMonitor monitor) throws CoreException { IIndex index = CCorePlugin.getIndexManager().getIndex(projects); try { index.acquireReadLock(); long start = System.currentTimeMillis(); IIndexBinding[] all = index.findBindings(Pattern.compile(".*"), false, new IndexFilter() { //$NON-NLS-1$ @Override public boolean acceptBinding(IBinding binding) throws CoreException { return IndexFilter.ALL_DECLARED_OR_IMPLICIT.acceptBinding(binding) && IndexModelUtil.bindingHasCElementType(binding, kinds); }}, monitor ); if(DEBUG) { System.out.println("Index search took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } ITypeInfo[] result = new ITypeInfo[all.length]; for(int i=0; i<all.length; i++) { result[i] = IndexTypeInfo.create(index, all[i]); } if(DEBUG) { System.out.println("Wrapping as ITypeInfo took "+(System.currentTimeMillis() - start)); //$NON-NLS-1$ start = System.currentTimeMillis(); } return result; } catch(InterruptedException ie) { ie.printStackTrace(); } finally { index.releaseReadLock(); } return new ITypeInfo[0]; }
diff --git a/org.aspectj.matcher/src/org/aspectj/weaver/patterns/PatternParser.java b/org.aspectj.matcher/src/org/aspectj/weaver/patterns/PatternParser.java index d1ecd551b..75929e7a1 100644 --- a/org.aspectj.matcher/src/org/aspectj/weaver/patterns/PatternParser.java +++ b/org.aspectj.matcher/src/org/aspectj/weaver/patterns/PatternParser.java @@ -1,1605 +1,1613 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer many updates since.... * ******************************************************************/ package org.aspectj.weaver.patterns; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.internal.tools.PointcutDesignatorHandlerBasedPointcut; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.ContextBasedMatcher; import org.aspectj.weaver.tools.PointcutDesignatorHandler; //XXX doesn't handle errors for extra tokens very well (sometimes ignores) public class PatternParser { private ITokenSource tokenSource; private ISourceContext sourceContext; /** not thread-safe, but this class is not intended to be... */ private boolean allowHasTypePatterns = false; /** extension handlers used in weaver tools API only */ private Set pointcutDesignatorHandlers = Collections.EMPTY_SET; private ReflectionWorld world; /** * Constructor for PatternParser. */ public PatternParser(ITokenSource tokenSource) { super(); this.tokenSource = tokenSource; this.sourceContext = tokenSource.getSourceContext(); } /** only used by weaver tools API */ public void setPointcutDesignatorHandlers(Set handlers, ReflectionWorld world) { this.pointcutDesignatorHandlers = handlers; this.world = world; } public PerClause maybeParsePerClause() { IToken tok = tokenSource.peek(); if (tok == IToken.EOF) return null; if (tok.isIdentifier()) { String name = tok.getString(); if (name.equals("issingleton")) { return parsePerSingleton(); } else if (name.equals("perthis")) { return parsePerObject(true); } else if (name.equals("pertarget")) { return parsePerObject(false); } else if (name.equals("percflow")) { return parsePerCflow(false); } else if (name.equals("percflowbelow")) { return parsePerCflow(true); } else if (name.equals("pertypewithin")) { // PTWIMPL Parse the pertypewithin clause return parsePerTypeWithin(); } else { return null; } } return null; } private PerClause parsePerCflow(boolean isBelow) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerCflow(entry, isBelow); } private PerClause parsePerObject(boolean isThis) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerObject(entry, isThis); } private PerClause parsePerTypeWithin() { parseIdentifier(); eat("("); TypePattern withinTypePattern = parseTypePattern(); eat(")"); return new PerTypeWithin(withinTypePattern); } private PerClause parsePerSingleton() { parseIdentifier(); eat("("); eat(")"); return new PerSingleton(); } public Declare parseDeclare() { int startPos = tokenSource.peek().getStart(); eatIdentifier("declare"); String kind = parseIdentifier(); Declare ret; if (kind.equals("error")) { eat(":"); ret = parseErrorOrWarning(true); } else if (kind.equals("warning")) { eat(":"); ret = parseErrorOrWarning(false); } else if (kind.equals("precedence")) { eat(":"); ret = parseDominates(); } else if (kind.equals("dominates")) { throw new ParserException("name changed to declare precedence", tokenSource.peek(-2)); } else if (kind.equals("parents")) { ret = parseParents(); } else if (kind.equals("soft")) { eat(":"); ret = parseSoft(); } else { throw new ParserException( "expected one of error, warning, parents, soft, precedence, @type, @method, @constructor, @field", tokenSource .peek(-1)); } int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } public Declare parseDeclareAnnotation() { int startPos = tokenSource.peek().getStart(); eatIdentifier("declare"); eat("@"); String kind = parseIdentifier(); eat(":"); Declare ret; if (kind.equals("type")) { ret = parseDeclareAtType(); } else if (kind.equals("method")) { ret = parseDeclareAtMethod(true); } else if (kind.equals("field")) { ret = parseDeclareAtField(); } else if (kind.equals("constructor")) { ret = parseDeclareAtMethod(false); } else { throw new ParserException("one of type, method, field, constructor", tokenSource.peek(-1)); } eat(";"); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } public DeclareAnnotation parseDeclareAtType() { allowHasTypePatterns = true; TypePattern p = parseTypePattern(); allowHasTypePatterns = false; return new DeclareAnnotation(DeclareAnnotation.AT_TYPE, p); } public DeclareAnnotation parseDeclareAtMethod(boolean isMethod) { if (maybeEat("(")) { DeclareAnnotation da = parseDeclareAtMethod(isMethod); eat(")", "missing ')' - unbalanced parentheses around signature pattern in declare @" + (isMethod ? "method" : "constructor")); return da; } SignaturePattern sp = parseMethodOrConstructorSignaturePattern(); boolean isConstructorPattern = (sp.getKind() == Member.CONSTRUCTOR); if (isMethod && isConstructorPattern) { throw new ParserException("method signature pattern", tokenSource.peek(-1)); } if (!isMethod && !isConstructorPattern) { throw new ParserException("constructor signature pattern", tokenSource.peek(-1)); } if (isConstructorPattern) return new DeclareAnnotation(DeclareAnnotation.AT_CONSTRUCTOR, sp); else return new DeclareAnnotation(DeclareAnnotation.AT_METHOD, sp); } public DeclareAnnotation parseDeclareAtField() { if (maybeEat("(")) { DeclareAnnotation da = parseDeclareAtField(); eat(")", "missing ')' - unbalanced parentheses around field signature pattern in declare @field"); return da; } SignaturePattern fieldSigPattern = parseFieldSignaturePattern(); return new DeclareAnnotation(DeclareAnnotation.AT_FIELD, fieldSigPattern); } public DeclarePrecedence parseDominates() { List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); return new DeclarePrecedence(l); } private Declare parseParents() { /* * simplified design requires use of raw types for declare parents, no generic spec. allowed String[] typeParameters = * maybeParseSimpleTypeVariableList(); */ eat(":"); allowHasTypePatterns = true; TypePattern p = parseTypePattern(false, false); allowHasTypePatterns = false; IToken t = tokenSource.next(); if (!(t.getString().equals("extends") || t.getString().equals("implements"))) { throw new ParserException("extends or implements", t); } boolean isExtends = t.getString().equals("extends"); List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); // XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns DeclareParents decp = new DeclareParents(p, l, isExtends); return decp; } private Declare parseSoft() { TypePattern p = parseTypePattern(); eat(":"); Pointcut pointcut = parsePointcut(); return new DeclareSoft(p, pointcut); } private Declare parseErrorOrWarning(boolean isError) { Pointcut pointcut = parsePointcut(); eat(":"); String message = parsePossibleStringSequence(true); return new DeclareErrorOrWarning(isError, pointcut, message); } public Pointcut parsePointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parseNotOrPointcut()); } if (maybeEat("||")) { p = new OrPointcut(p, parsePointcut()); } return p; } private Pointcut parseNotOrPointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parsePointcut()); } return p; } private Pointcut parseAtomicPointcut() { if (maybeEat("!")) { int startPos = tokenSource.peek(-1).getStart(); Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos); return p; } if (maybeEat("(")) { Pointcut p = parsePointcut(); eat(")"); return p; } if (maybeEat("@")) { int startPos = tokenSource.peek().getStart(); Pointcut p = parseAnnotationPointcut(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } int startPos = tokenSource.peek().getStart(); Pointcut p = parseSinglePointcut(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } public Pointcut parseSinglePointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); Pointcut p = t.maybeGetParsedPointcut(); if (p != null) { tokenSource.next(); return p; } String kind = parseIdentifier(); // IToken possibleTypeVariableToken = tokenSource.peek(); // String[] typeVariables = maybeParseSimpleTypeVariableList(); if (kind.equals("execution") || kind.equals("call") || kind.equals("get") || kind.equals("set")) { p = parseKindedPointcut(kind); } else if (kind.equals("args")) { p = parseArgsPointcut(); } else if (kind.equals("this")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("target")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("within")) { p = parseWithinPointcut(); } else if (kind.equals("withincode")) { p = parseWithinCodePointcut(); } else if (kind.equals("cflow")) { p = parseCflowPointcut(false); } else if (kind.equals("cflowbelow")) { p = parseCflowPointcut(true); } else if (kind.equals("adviceexecution")) { eat("("); eat(")"); p = new KindedPointcut(Shadow.AdviceExecution, new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("handler")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new HandlerPointcut(typePat); } else if (kind.equals("lock") || kind.equals("unlock")) { p = parseMonitorPointcut(kind); } else if (kind.equals("initialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.Initialization, sig); } else if (kind.equals("staticinitialization")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new KindedPointcut(Shadow.StaticInitialization, new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("preinitialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.PreInitialization, sig); } else if (kind.equals("if")) { - // @style support allows if(), if(true), if(false) + // - annotation style only allows if(), if(true) or if(false) + // - if() means the body of the annotated method represents the if expression + // - anything else is an error because code cannot be put into the if() + // - code style will already have been processed and the call to maybeGetParsedPointcut() + // at the top of this method will have succeeded. eat("("); if (maybeEatIdentifier("true")) { eat(")"); p = new IfPointcut.IfTruePointcut(); } else if (maybeEatIdentifier("false")) { eat(")"); p = new IfPointcut.IfFalsePointcut(); } else { - eat(")"); + if (!maybeEat(")")) { + throw new ParserException( + "in annotation style, if(...) pointcuts cannot contain code. Use if() and put the code in the annotated method", + t); + } // TODO - Alex has some token stuff going on here to get a readable name in place of ""... p = new IfPointcut(""); } } else { boolean matchedByExtensionDesignator = false; // see if a registered handler wants to parse it, otherwise // treat as a reference pointcut for (Iterator iter = this.pointcutDesignatorHandlers.iterator(); iter.hasNext();) { PointcutDesignatorHandler pcd = (PointcutDesignatorHandler) iter.next(); if (pcd.getDesignatorName().equals(kind)) { p = parseDesignatorPointcut(pcd); matchedByExtensionDesignator = true; } } if (!matchedByExtensionDesignator) { tokenSource.setIndex(start); p = parseReferencePointcut(); } } return p; } private void assertNoTypeVariables(String[] tvs, String errorMessage, IToken token) { if (tvs != null) throw new ParserException(errorMessage, token); } public Pointcut parseAnnotationPointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); String kind = parseIdentifier(); IToken possibleTypeVariableToken = tokenSource.peek(); String[] typeVariables = maybeParseSimpleTypeVariableList(); if (typeVariables != null) { String message = "("; assertNoTypeVariables(typeVariables, message, possibleTypeVariableToken); } tokenSource.setIndex(start); if (kind.equals("annotation")) { return parseAtAnnotationPointcut(); } else if (kind.equals("args")) { return parseArgsAnnotationPointcut(); } else if (kind.equals("this") || kind.equals("target")) { return parseThisOrTargetAnnotationPointcut(); } else if (kind.equals("within")) { return parseWithinAnnotationPointcut(); } else if (kind.equals("withincode")) { return parseWithinCodeAnnotationPointcut(); } throw new ParserException("pointcut name", t); } private Pointcut parseAtAnnotationPointcut() { parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("@AnnotationName or parameter", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new AnnotationPointcut(type); } private SignaturePattern parseConstructorSignaturePattern() { SignaturePattern ret = parseMethodOrConstructorSignaturePattern(); if (ret.getKind() == Member.CONSTRUCTOR) return ret; throw new ParserException("constructor pattern required, found method pattern", ret); } private Pointcut parseWithinCodePointcut() { // parseIdentifier(); eat("("); SignaturePattern sig = parseMethodOrConstructorSignaturePattern(); eat(")"); return new WithincodePointcut(sig); } private Pointcut parseCflowPointcut(boolean isBelow) { // parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new CflowPointcut(entry, isBelow, null); } /** * Method parseWithinPointcut. * * @return Pointcut */ private Pointcut parseWithinPointcut() { // parseIdentifier(); eat("("); TypePattern type = parseTypePattern(); eat(")"); return new WithinPointcut(type); } /** * Method parseThisOrTargetPointcut. * * @return Pointcut */ private Pointcut parseThisOrTargetPointcut(String kind) { eat("("); TypePattern type = parseTypePattern(); eat(")"); return new ThisOrTargetPointcut(kind.equals("this"), type); } private Pointcut parseThisOrTargetAnnotationPointcut() { String kind = parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new ThisOrTargetAnnotationPointcut(kind.equals("this"), type); } private Pointcut parseWithinAnnotationPointcut() { /* String kind = */parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } AnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new WithinAnnotationPointcut(type); } private Pointcut parseWithinCodeAnnotationPointcut() { /* String kind = */parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new WithinCodeAnnotationPointcut(type); } /** * Method parseArgsPointcut. * * @return Pointcut */ private Pointcut parseArgsPointcut() { // parseIdentifier(); TypePatternList arguments = parseArgumentsPattern(false); return new ArgsPointcut(arguments); } private Pointcut parseArgsAnnotationPointcut() { parseIdentifier(); AnnotationPatternList arguments = parseArgumentsAnnotationPattern(); return new ArgsAnnotationPointcut(arguments); } private Pointcut parseReferencePointcut() { TypePattern onType = parseTypePattern(); NamePattern name = null; if (onType.typeParameters.size() > 0) { eat("."); name = parseNamePattern(); } else { name = tryToExtractName(onType); } if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } if (onType.toString().equals("")) { onType = null; } String simpleName = name.maybeGetSimpleName(); if (simpleName == null) { throw new ParserException("(", tokenSource.peek(-1)); } TypePatternList arguments = parseArgumentsPattern(false); return new ReferencePointcut(onType, simpleName, arguments); } private Pointcut parseDesignatorPointcut(PointcutDesignatorHandler pcdHandler) { eat("("); int parenCount = 1; StringBuffer pointcutBody = new StringBuffer(); while (parenCount > 0) { if (maybeEat("(")) { parenCount++; pointcutBody.append("("); } else if (maybeEat(")")) { parenCount--; if (parenCount > 0) { pointcutBody.append(")"); } } else { pointcutBody.append(nextToken().getString()); } } ContextBasedMatcher pcExpr = pcdHandler.parse(pointcutBody.toString()); return new PointcutDesignatorHandlerBasedPointcut(pcExpr, world); } public List parseDottedIdentifier() { List ret = new ArrayList(); ret.add(parseIdentifier()); while (maybeEat(".")) { ret.add(parseIdentifier()); } return ret; } private KindedPointcut parseKindedPointcut(String kind) { eat("("); SignaturePattern sig; Shadow.Kind shadowKind = null; if (kind.equals("execution")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodExecution; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorExecution; } } else if (kind.equals("call")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodCall; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorCall; } } else if (kind.equals("get")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldGet; } else if (kind.equals("set")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldSet; } else { throw new ParserException("bad kind: " + kind, tokenSource.peek()); } eat(")"); return new KindedPointcut(shadowKind, sig); } /** Covers the 'lock()' and 'unlock()' pointcuts */ private KindedPointcut parseMonitorPointcut(String kind) { eat("("); // TypePattern type = TypePattern.ANY; eat(")"); if (kind.equals("lock")) { return new KindedPointcut(Shadow.SynchronizationLock, new SignaturePattern(Member.MONITORENTER, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, // type, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else { return new KindedPointcut(Shadow.SynchronizationUnlock, new SignaturePattern(Member.MONITORENTER, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, // type, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } } public TypePattern parseTypePattern() { return parseTypePattern(false, false); } public TypePattern parseTypePattern(boolean insideTypeParameters, boolean parameterAnnotationsPossible) { TypePattern p = parseAtomicTypePattern(insideTypeParameters, parameterAnnotationsPossible); if (maybeEat("&&")) { p = new AndTypePattern(p, parseNotOrTypePattern(insideTypeParameters, parameterAnnotationsPossible)); } if (maybeEat("||")) { p = new OrTypePattern(p, parseTypePattern(insideTypeParameters, parameterAnnotationsPossible)); } return p; } private TypePattern parseNotOrTypePattern(boolean insideTypeParameters, boolean parameterAnnotationsPossible) { TypePattern p = parseAtomicTypePattern(insideTypeParameters, parameterAnnotationsPossible); if (maybeEat("&&")) { p = new AndTypePattern(p, parseTypePattern(insideTypeParameters, parameterAnnotationsPossible)); } return p; } // Need to differentiate in here between two kinds of annotation pattern - depending on where the ( is private TypePattern parseAtomicTypePattern(boolean insideTypeParameters, boolean parameterAnnotationsPossible) { AnnotationTypePattern ap = maybeParseAnnotationPattern(); // might be parameter annotation pattern or type annotation // pattern if (maybeEat("!")) { // int startPos = tokenSource.peek(-1).getStart(); // ??? we lose source location for true start of !type // An annotation, if processed, is outside of the Not - so here we have to build // an And pattern containing the annotation and the not as left and right children // *unless* the annotation pattern was just 'Any' then we can skip building the // And and just return the Not directly (pr228980) TypePattern p = null; TypePattern tp = parseAtomicTypePattern(insideTypeParameters, parameterAnnotationsPossible); if (!(ap instanceof AnyAnnotationTypePattern)) { p = new NotTypePattern(tp); p = new AndTypePattern(setAnnotationPatternForTypePattern(TypePattern.ANY, ap, false), p); } else { p = new NotTypePattern(tp); } return p; } if (maybeEat("(")) { TypePattern p = parseTypePattern(insideTypeParameters, false); if ((p instanceof NotTypePattern) && !(ap instanceof AnyAnnotationTypePattern)) { // dont set the annotation on it, we don't want the annotation to be // considered as part of the not, it is outside the not (pr228980) TypePattern tp = setAnnotationPatternForTypePattern(TypePattern.ANY, ap, parameterAnnotationsPossible); p = new AndTypePattern(tp, p); } else { p = setAnnotationPatternForTypePattern(p, ap, parameterAnnotationsPossible); } eat(")"); boolean isVarArgs = maybeEat("..."); if (isVarArgs) p.setIsVarArgs(isVarArgs); boolean isIncludeSubtypes = maybeEat("+"); if (isIncludeSubtypes) p.includeSubtypes = true; // need the test because (A+) should not set subtypes to false! return p; } int startPos = tokenSource.peek().getStart(); TypePattern p = parseSingleTypePattern(insideTypeParameters); int endPos = tokenSource.peek(-1).getEnd(); p = setAnnotationPatternForTypePattern(p, ap, false); p.setLocation(sourceContext, startPos, endPos); return p; } private TypePattern setAnnotationPatternForTypePattern(TypePattern t, AnnotationTypePattern ap, boolean parameterAnnotationsPattern) { TypePattern ret = t; if (parameterAnnotationsPattern) ap.setForParameterAnnotationMatch(); if (ap != AnnotationTypePattern.ANY) { if (t == TypePattern.ANY) { ret = new WildTypePattern(new NamePattern[] { NamePattern.ANY }, false, 0, false, null); } if (t.annotationPattern == AnnotationTypePattern.ANY) { ret.setAnnotationTypePattern(ap); } else { ret.setAnnotationTypePattern(new AndAnnotationTypePattern(ap, t.annotationPattern)); // ??? } } return ret; } public AnnotationTypePattern maybeParseAnnotationPattern() { AnnotationTypePattern ret = AnnotationTypePattern.ANY; AnnotationTypePattern nextPattern = null; while ((nextPattern = maybeParseSingleAnnotationPattern()) != null) { if (ret == AnnotationTypePattern.ANY) { ret = nextPattern; } else { ret = new AndAnnotationTypePattern(ret, nextPattern); } } return ret; } // PVAL cope with annotation values at other places in this code public AnnotationTypePattern maybeParseSingleAnnotationPattern() { AnnotationTypePattern ret = null; Map values = null; // LALR(2) - fix by making "!@" a single token int startIndex = tokenSource.getIndex(); if (maybeEat("!")) { if (maybeEat("@")) { if (maybeEat("(")) { TypePattern p = parseTypePattern(); ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p)); eat(")"); return ret; } else { TypePattern p = parseSingleTypePattern(); if (maybeEatAdjacent("(")) { values = parseAnnotationValues(); eat(")"); ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p, values)); } else { ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p)); } return ret; } } else { tokenSource.setIndex(startIndex); // not for us! return ret; } } if (maybeEat("@")) { if (maybeEat("(")) { TypePattern p = parseTypePattern(); ret = new WildAnnotationTypePattern(p); eat(")"); return ret; } else { TypePattern p = parseSingleTypePattern(); if (maybeEatAdjacent("(")) { values = parseAnnotationValues(); eat(")"); ret = new WildAnnotationTypePattern(p, values); } else { ret = new WildAnnotationTypePattern(p); } return ret; } } else { tokenSource.setIndex(startIndex); // not for us! return ret; } } // Parse annotation values. In an expression in @A(a=b,c=d) this method will be // parsing the a=b,c=d.) public Map/* String,String */parseAnnotationValues() { Map values = new HashMap(); boolean seenDefaultValue = false; do { String possibleKeyString = parseAnnotationNameValuePattern(); if (possibleKeyString == null) { throw new ParserException("expecting simple literal ", tokenSource.peek(-1)); } // did they specify just a single entry 'v' or a keyvalue pair 'k=v' if (maybeEat("=")) { // it was a key! String valueString = parseAnnotationNameValuePattern(); if (valueString == null) { throw new ParserException("expecting simple literal ", tokenSource.peek(-1)); } values.put(possibleKeyString, valueString); } else { if (seenDefaultValue) { throw new ParserException("cannot specify two default values", tokenSource.peek(-1)); } seenDefaultValue = true; values.put("value", possibleKeyString); } } while (maybeEat(",")); // keep going whilst there are ',' return values; } public TypePattern parseSingleTypePattern() { return parseSingleTypePattern(false); } public TypePattern parseSingleTypePattern(boolean insideTypeParameters) { if (insideTypeParameters && maybeEat("?")) return parseGenericsWildcardTypePattern(); if (allowHasTypePatterns) { if (maybeEatIdentifier("hasmethod")) return parseHasMethodTypePattern(); if (maybeEatIdentifier("hasfield")) return parseHasFieldTypePattern(); } List names = parseDottedNamePattern(); int dim = 0; while (maybeEat("[")) { eat("]"); dim++; } TypePatternList typeParameters = maybeParseTypeParameterList(); int endPos = tokenSource.peek(-1).getEnd(); boolean isVarArgs = maybeEat("..."); boolean includeSubtypes = maybeEat("+"); // ??? what about the source location of any's???? if (names.size() == 1 && ((NamePattern) names.get(0)).isAny() && dim == 0 && !isVarArgs && typeParameters == null) return TypePattern.ANY; // Notice we increase the dimensions if varargs is set. this is to allow type matching to // succeed later: The actual signature at runtime of a method declared varargs is an array type of // the original declared type (so Integer... becomes Integer[] in the bytecode). So, here for the // pattern 'Integer...' we create a WildTypePattern 'Integer[]' with varargs set. If this matches // during shadow matching, we confirm that the varargs flags match up before calling it a successful // match. return new WildTypePattern(names, includeSubtypes, dim + (isVarArgs ? 1 : 0), endPos, isVarArgs, typeParameters); } public TypePattern parseHasMethodTypePattern() { int startPos = tokenSource.peek(-1).getStart(); eat("("); SignaturePattern sp = parseMethodOrConstructorSignaturePattern(); eat(")"); int endPos = tokenSource.peek(-1).getEnd(); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.setLocation(sourceContext, startPos, endPos); return ret; } public TypePattern parseHasFieldTypePattern() { int startPos = tokenSource.peek(-1).getStart(); eat("("); SignaturePattern sp = parseFieldSignaturePattern(); eat(")"); int endPos = tokenSource.peek(-1).getEnd(); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.setLocation(sourceContext, startPos, endPos); return ret; } public TypePattern parseGenericsWildcardTypePattern() { List names = new ArrayList(); names.add(new NamePattern("?")); TypePattern upperBound = null; TypePattern[] additionalInterfaceBounds = new TypePattern[0]; TypePattern lowerBound = null; if (maybeEatIdentifier("extends")) { upperBound = parseTypePattern(false, false); additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds(); } if (maybeEatIdentifier("super")) { lowerBound = parseTypePattern(false, false); } int endPos = tokenSource.peek(-1).getEnd(); return new WildTypePattern(names, false, 0, endPos, false, null, upperBound, additionalInterfaceBounds, lowerBound); } // private AnnotationTypePattern completeAnnotationPattern(AnnotationTypePattern p) { // if (maybeEat("&&")) { // return new AndAnnotationTypePattern(p,parseNotOrAnnotationPattern()); // } // if (maybeEat("||")) { // return new OrAnnotationTypePattern(p,parseAnnotationTypePattern()); // } // return p; // } // // protected AnnotationTypePattern parseAnnotationTypePattern() { // AnnotationTypePattern ap = parseAtomicAnnotationPattern(); // if (maybeEat("&&")) { // ap = new AndAnnotationTypePattern(ap, parseNotOrAnnotationPattern()); // } // // if (maybeEat("||")) { // ap = new OrAnnotationTypePattern(ap, parseAnnotationTypePattern()); // } // return ap; // } // // private AnnotationTypePattern parseNotOrAnnotationPattern() { // AnnotationTypePattern p = parseAtomicAnnotationPattern(); // if (maybeEat("&&")) { // p = new AndAnnotationTypePattern(p,parseAnnotationTypePattern()); // } // return p; // } protected ExactAnnotationTypePattern parseAnnotationNameOrVarTypePattern() { ExactAnnotationTypePattern p = null; int startPos = tokenSource.peek().getStart(); if (maybeEat("@")) { throw new ParserException("@Foo form was deprecated in AspectJ 5 M2: annotation name or var ", tokenSource.peek(-1)); } p = parseSimpleAnnotationName(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); // For optimized syntax that allows binding directly to annotation values (pr234943) if (maybeEat("(")) { String formalName = parseIdentifier(); p = new ExactAnnotationFieldTypePattern(p, formalName); eat(")"); } return p; } /** * @return */ private ExactAnnotationTypePattern parseSimpleAnnotationName() { // the @ has already been eaten... ExactAnnotationTypePattern p; StringBuffer annotationName = new StringBuffer(); annotationName.append(parseIdentifier()); while (maybeEat(".")) { annotationName.append('.'); annotationName.append(parseIdentifier()); } UnresolvedType type = UnresolvedType.forName(annotationName.toString()); p = new ExactAnnotationTypePattern(type, null); return p; } // private AnnotationTypePattern parseAtomicAnnotationPattern() { // if (maybeEat("!")) { // //int startPos = tokenSource.peek(-1).getStart(); // //??? we lose source location for true start of !type // AnnotationTypePattern p = new NotAnnotationTypePattern(parseAtomicAnnotationPattern()); // return p; // } // if (maybeEat("(")) { // AnnotationTypePattern p = parseAnnotationTypePattern(); // eat(")"); // return p; // } // int startPos = tokenSource.peek().getStart(); // eat("@"); // StringBuffer annotationName = new StringBuffer(); // annotationName.append(parseIdentifier()); // while (maybeEat(".")) { // annotationName.append('.'); // annotationName.append(parseIdentifier()); // } // UnresolvedType type = UnresolvedType.forName(annotationName.toString()); // AnnotationTypePattern p = new ExactAnnotationTypePattern(type); // int endPos = tokenSource.peek(-1).getEnd(); // p.setLocation(sourceContext, startPos, endPos); // return p; // } public List parseDottedNamePattern() { List names = new ArrayList(); StringBuffer buf = new StringBuffer(); IToken previous = null; boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536) boolean justProcessedDot = false; boolean onADot = false; while (true) { IToken tok = null; int startPos = tokenSource.peek().getStart(); String afterDot = null; while (true) { if (previous != null && previous.getString().equals(".")) justProcessedDot = true; tok = tokenSource.peek(); onADot = (tok.getString().equals(".")); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || (tok.isIdentifier() && tok.getString() != "...")) { buf.append(tok.getString()); } else if (tok.getString() == "...") { break; } else if (tok.getLiteralKind() != null) { // System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); int dot = s.indexOf('.'); if (dot != -1) { buf.append(s.substring(0, dot)); afterDot = s.substring(dot + 1); previous = tokenSource.next(); break; } buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); // XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0 && names.isEmpty()) { throw new ParserException("name pattern", tok); } if (buf.length() == 0 && justProcessedEllipsis) { throw new ParserException("name pattern cannot finish with ..", tok); } if (buf.length() == 0 && justProcessedDot && !onADot) { throw new ParserException("name pattern cannot finish with .", tok); } if (buf.length() == 0) { names.add(NamePattern.ELLIPSIS); justProcessedEllipsis = true; } else { checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); names.add(ret); justProcessedEllipsis = false; } if (afterDot == null) { buf.setLength(0); // no elipsis or dotted name part if (!maybeEat(".")) break; // go on else previous = tokenSource.peek(-1); } else { buf.setLength(0); buf.append(afterDot); afterDot = null; } } // System.err.println("parsed: " + names); return names; } // supported form 'a.b.c.d' or just 'a' public String parseAnnotationNameValuePattern() { StringBuffer buf = new StringBuffer(); IToken tok; // int startPos = tokenSource.peek().getStart(); boolean dotOK = false; int depth = 0; while (true) { tok = tokenSource.peek(); // keep going until we hit ')' or '=' or ',' if (tok.getString() == ")" && depth == 0) break; if (tok.getString() == "=" && depth == 0) break; if (tok.getString() == "," && depth == 0) break; // keep track of nested brackets if (tok.getString() == "(") depth++; if (tok.getString() == ")") depth--; if (tok.getString() == "{") depth++; if (tok.getString() == "}") depth--; if (tok.getString() == "." && !dotOK) { throw new ParserException("dot not expected", tok); } buf.append(tok.getString()); tokenSource.next(); dotOK = true; } if (buf.length() == 0) return null; else return buf.toString(); } public NamePattern parseNamePattern() { StringBuffer buf = new StringBuffer(); IToken previous = null; IToken tok; int startPos = tokenSource.peek().getStart(); while (true) { tok = tokenSource.peek(); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || tok.isIdentifier()) { buf.append(tok.getString()); } else if (tok.getLiteralKind() != null) { // System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); if (s.indexOf('.') != -1) break; buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); // XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0) { throw new ParserException("name pattern", tok); } checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); return ret; } private void checkLegalName(String s, IToken tok) { char ch = s.charAt(0); if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) { throw new ParserException("illegal identifier start (" + ch + ")", tok); } for (int i = 1, len = s.length(); i < len; i++) { ch = s.charAt(i); if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) { throw new ParserException("illegal identifier character (" + ch + ")", tok); } } } private boolean isAdjacent(IToken first, IToken second) { return first.getEnd() == second.getStart() - 1; } public ModifiersPattern parseModifiersPattern() { int requiredFlags = 0; int forbiddenFlags = 0; int start; while (true) { start = tokenSource.getIndex(); boolean isForbidden = false; isForbidden = maybeEat("!"); IToken t = tokenSource.next(); int flag = ModifiersPattern.getModifierFlag(t.getString()); if (flag == -1) break; if (isForbidden) forbiddenFlags |= flag; else requiredFlags |= flag; } tokenSource.setIndex(start); if (requiredFlags == 0 && forbiddenFlags == 0) { return ModifiersPattern.ANY; } else { return new ModifiersPattern(requiredFlags, forbiddenFlags); } } public TypePatternList parseArgumentsPattern(boolean parameterAnnotationsPossible) { List patterns = new ArrayList(); eat("("); // () if (maybeEat(")")) { return new TypePatternList(); } do { if (maybeEat(".")) { // .. eat("."); patterns.add(TypePattern.ELLIPSIS); } else { patterns.add(parseTypePattern(false, parameterAnnotationsPossible)); } } while (maybeEat(",")); eat(")"); return new TypePatternList(patterns); } public AnnotationPatternList parseArgumentsAnnotationPattern() { List patterns = new ArrayList(); eat("("); if (maybeEat(")")) { return new AnnotationPatternList(); } do { if (maybeEat(".")) { eat("."); patterns.add(AnnotationTypePattern.ELLIPSIS); } else if (maybeEat("*")) { patterns.add(AnnotationTypePattern.ANY); } else { patterns.add(parseAnnotationNameOrVarTypePattern()); } } while (maybeEat(",")); eat(")"); return new AnnotationPatternList(patterns); } public ThrowsPattern parseOptionalThrowsPattern() { IToken t = tokenSource.peek(); if (t.isIdentifier() && t.getString().equals("throws")) { tokenSource.next(); List required = new ArrayList(); List forbidden = new ArrayList(); do { boolean isForbidden = maybeEat("!"); // ???might want an error for a second ! without a paren TypePattern p = parseTypePattern(); if (isForbidden) forbidden.add(p); else required.add(p); } while (maybeEat(",")); return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden)); } return ThrowsPattern.ANY; } public SignaturePattern parseMethodOrConstructorSignaturePattern() { int startPos = tokenSource.peek().getStart(); AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(false, false); TypePattern declaringType; NamePattern name = null; MemberKind kind; // here we can check for 'new' if (maybeEatNew(returnType)) { kind = Member.CONSTRUCTOR; if (returnType.toString().length() == 0) { declaringType = TypePattern.ANY; } else { declaringType = returnType; } returnType = TypePattern.ANY; name = NamePattern.ANY; } else { kind = Member.METHOD; IToken nameToken = tokenSource.peek(); declaringType = parseTypePattern(false, false); if (maybeEat(".")) { nameToken = tokenSource.peek(); name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } String simpleName = name.maybeGetSimpleName(); // XXX should add check for any Java keywords if (simpleName != null && simpleName.equals("new")) { throw new ParserException("method name (not constructor)", nameToken); } } TypePatternList parameterTypes = parseArgumentsPattern(true); ThrowsPattern throwsPattern = parseOptionalThrowsPattern(); SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern, annotationPattern); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private boolean maybeEatNew(TypePattern returnType) { if (returnType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern) returnType; if (p.maybeExtractName("new")) return true; } int start = tokenSource.getIndex(); if (maybeEat(".")) { String id = maybeEatIdentifier(); if (id != null && id.equals("new")) return true; tokenSource.setIndex(start); } return false; } public SignaturePattern parseFieldSignaturePattern() { int startPos = tokenSource.peek().getStart(); // TypePatternList followMe = TypePatternList.ANY; AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(); TypePattern declaringType = parseTypePattern(); NamePattern name; // System.err.println("parsed field: " + declaringType.toString()); if (maybeEat(".")) { name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (name == null) throw new ParserException("name pattern", tokenSource.peek()); if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType, declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY, annotationPattern); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private NamePattern tryToExtractName(TypePattern nextType) { if (nextType == TypePattern.ANY) { return NamePattern.ANY; } else if (nextType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern) nextType; return p.extractName(); } else { return null; } } /** * Parse type variable declarations for a generic method or at the start of a signature pointcut to identify type variable names * in a generic type. * * @param includeParameterizedTypes * @return */ public TypeVariablePatternList maybeParseTypeVariableList() { if (!maybeEat("<")) return null; List typeVars = new ArrayList(); TypeVariablePattern t = parseTypeVariable(); typeVars.add(t); while (maybeEat(",")) { TypeVariablePattern nextT = parseTypeVariable(); typeVars.add(nextT); } eat(">"); TypeVariablePattern[] tvs = new TypeVariablePattern[typeVars.size()]; typeVars.toArray(tvs); return new TypeVariablePatternList(tvs); } // of the form execution<T,S,V> - allows identifiers only public String[] maybeParseSimpleTypeVariableList() { if (!maybeEat("<")) return null; List typeVarNames = new ArrayList(); do { typeVarNames.add(parseIdentifier()); } while (maybeEat(",")); eat(">", "',' or '>'"); String[] tvs = new String[typeVarNames.size()]; typeVarNames.toArray(tvs); return tvs; } public TypePatternList maybeParseTypeParameterList() { if (!maybeEat("<")) return null; List typePats = new ArrayList(); do { TypePattern tp = parseTypePattern(true, false); typePats.add(tp); } while (maybeEat(",")); eat(">"); TypePattern[] tps = new TypePattern[typePats.size()]; typePats.toArray(tps); return new TypePatternList(tps); } public TypeVariablePattern parseTypeVariable() { TypePattern upperBound = null; TypePattern[] additionalInterfaceBounds = null; TypePattern lowerBound = null; String typeVariableName = parseIdentifier(); if (maybeEatIdentifier("extends")) { upperBound = parseTypePattern(); additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds(); } else if (maybeEatIdentifier("super")) { lowerBound = parseTypePattern(); } return new TypeVariablePattern(typeVariableName, upperBound, additionalInterfaceBounds, lowerBound); } private TypePattern[] maybeParseAdditionalInterfaceBounds() { List boundsList = new ArrayList(); while (maybeEat("&")) { TypePattern tp = parseTypePattern(); boundsList.add(tp); } if (boundsList.size() == 0) return null; TypePattern[] ret = new TypePattern[boundsList.size()]; boundsList.toArray(ret); return ret; } public String parsePossibleStringSequence(boolean shouldEnd) { StringBuffer result = new StringBuffer(); IToken token = tokenSource.next(); if (token.getLiteralKind() == null) { throw new ParserException("string", token); } while (token.getLiteralKind().equals("string")) { result.append(token.getString()); boolean plus = maybeEat("+"); if (!plus) break; token = tokenSource.next(); if (token.getLiteralKind() == null) { throw new ParserException("string", token); } } eatIdentifier(";"); IToken t = tokenSource.next(); if (shouldEnd && t != IToken.EOF) { throw new ParserException("<string>;", token); } // bug 125027: since we've eaten the ";" we need to set the index // to be one less otherwise the end position isn't set correctly. int currentIndex = tokenSource.getIndex(); tokenSource.setIndex(currentIndex - 1); return result.toString(); } public String parseStringLiteral() { IToken token = tokenSource.next(); String literalKind = token.getLiteralKind(); if (literalKind == "string") { return token.getString(); } throw new ParserException("string", token); } public String parseIdentifier() { IToken token = tokenSource.next(); if (token.isIdentifier()) return token.getString(); throw new ParserException("identifier", token); } public void eatIdentifier(String expectedValue) { IToken next = tokenSource.next(); if (!next.getString().equals(expectedValue)) { throw new ParserException(expectedValue, next); } } public boolean maybeEatIdentifier(String expectedValue) { IToken next = tokenSource.peek(); if (next.getString().equals(expectedValue)) { tokenSource.next(); return true; } else { return false; } } public void eat(String expectedValue) { eat(expectedValue, expectedValue); } private void eat(String expectedValue, String expectedMessage) { IToken next = nextToken(); if (next.getString() != expectedValue) { if (expectedValue.equals(">") && next.getString().startsWith(">")) { // handle problem of >> and >>> being lexed as single tokens pendingRightArrows = BasicToken.makeLiteral(next.getString().substring(1).intern(), "string", next.getStart() + 1, next.getEnd()); return; } throw new ParserException(expectedMessage, next); } } private IToken pendingRightArrows; private IToken nextToken() { if (pendingRightArrows != null) { IToken ret = pendingRightArrows; pendingRightArrows = null; return ret; } else { return tokenSource.next(); } } public boolean maybeEatAdjacent(String token) { IToken next = tokenSource.peek(); if (next.getString() == token) { if (isAdjacent(tokenSource.peek(-1), next)) { tokenSource.next(); return true; } } return false; } public boolean maybeEat(String token) { IToken next = tokenSource.peek(); if (next.getString() == token) { tokenSource.next(); return true; } else { return false; } } public String maybeEatIdentifier() { IToken next = tokenSource.peek(); if (next.isIdentifier()) { tokenSource.next(); return next.getString(); } else { return null; } } public boolean peek(String token) { IToken next = tokenSource.peek(); return next.getString() == token; } public void checkEof() { IToken last = tokenSource.next(); if (last != IToken.EOF) { throw new ParserException("unexpected pointcut element", last); } } public PatternParser(String data) { this(BasicTokenSource.makeTokenSource(data, null)); } public PatternParser(String data, ISourceContext context) { this(BasicTokenSource.makeTokenSource(data, context)); } }
false
true
public Pointcut parseSinglePointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); Pointcut p = t.maybeGetParsedPointcut(); if (p != null) { tokenSource.next(); return p; } String kind = parseIdentifier(); // IToken possibleTypeVariableToken = tokenSource.peek(); // String[] typeVariables = maybeParseSimpleTypeVariableList(); if (kind.equals("execution") || kind.equals("call") || kind.equals("get") || kind.equals("set")) { p = parseKindedPointcut(kind); } else if (kind.equals("args")) { p = parseArgsPointcut(); } else if (kind.equals("this")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("target")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("within")) { p = parseWithinPointcut(); } else if (kind.equals("withincode")) { p = parseWithinCodePointcut(); } else if (kind.equals("cflow")) { p = parseCflowPointcut(false); } else if (kind.equals("cflowbelow")) { p = parseCflowPointcut(true); } else if (kind.equals("adviceexecution")) { eat("("); eat(")"); p = new KindedPointcut(Shadow.AdviceExecution, new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("handler")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new HandlerPointcut(typePat); } else if (kind.equals("lock") || kind.equals("unlock")) { p = parseMonitorPointcut(kind); } else if (kind.equals("initialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.Initialization, sig); } else if (kind.equals("staticinitialization")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new KindedPointcut(Shadow.StaticInitialization, new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("preinitialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.PreInitialization, sig); } else if (kind.equals("if")) { // @style support allows if(), if(true), if(false) eat("("); if (maybeEatIdentifier("true")) { eat(")"); p = new IfPointcut.IfTruePointcut(); } else if (maybeEatIdentifier("false")) { eat(")"); p = new IfPointcut.IfFalsePointcut(); } else { eat(")"); // TODO - Alex has some token stuff going on here to get a readable name in place of ""... p = new IfPointcut(""); } } else { boolean matchedByExtensionDesignator = false; // see if a registered handler wants to parse it, otherwise // treat as a reference pointcut for (Iterator iter = this.pointcutDesignatorHandlers.iterator(); iter.hasNext();) { PointcutDesignatorHandler pcd = (PointcutDesignatorHandler) iter.next(); if (pcd.getDesignatorName().equals(kind)) { p = parseDesignatorPointcut(pcd); matchedByExtensionDesignator = true; } } if (!matchedByExtensionDesignator) { tokenSource.setIndex(start); p = parseReferencePointcut(); } } return p; }
public Pointcut parseSinglePointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); Pointcut p = t.maybeGetParsedPointcut(); if (p != null) { tokenSource.next(); return p; } String kind = parseIdentifier(); // IToken possibleTypeVariableToken = tokenSource.peek(); // String[] typeVariables = maybeParseSimpleTypeVariableList(); if (kind.equals("execution") || kind.equals("call") || kind.equals("get") || kind.equals("set")) { p = parseKindedPointcut(kind); } else if (kind.equals("args")) { p = parseArgsPointcut(); } else if (kind.equals("this")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("target")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("within")) { p = parseWithinPointcut(); } else if (kind.equals("withincode")) { p = parseWithinCodePointcut(); } else if (kind.equals("cflow")) { p = parseCflowPointcut(false); } else if (kind.equals("cflowbelow")) { p = parseCflowPointcut(true); } else if (kind.equals("adviceexecution")) { eat("("); eat(")"); p = new KindedPointcut(Shadow.AdviceExecution, new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("handler")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new HandlerPointcut(typePat); } else if (kind.equals("lock") || kind.equals("unlock")) { p = parseMonitorPointcut(kind); } else if (kind.equals("initialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.Initialization, sig); } else if (kind.equals("staticinitialization")) { eat("("); TypePattern typePat = parseTypePattern(false, false); eat(")"); p = new KindedPointcut(Shadow.StaticInitialization, new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("preinitialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.PreInitialization, sig); } else if (kind.equals("if")) { // - annotation style only allows if(), if(true) or if(false) // - if() means the body of the annotated method represents the if expression // - anything else is an error because code cannot be put into the if() // - code style will already have been processed and the call to maybeGetParsedPointcut() // at the top of this method will have succeeded. eat("("); if (maybeEatIdentifier("true")) { eat(")"); p = new IfPointcut.IfTruePointcut(); } else if (maybeEatIdentifier("false")) { eat(")"); p = new IfPointcut.IfFalsePointcut(); } else { if (!maybeEat(")")) { throw new ParserException( "in annotation style, if(...) pointcuts cannot contain code. Use if() and put the code in the annotated method", t); } // TODO - Alex has some token stuff going on here to get a readable name in place of ""... p = new IfPointcut(""); } } else { boolean matchedByExtensionDesignator = false; // see if a registered handler wants to parse it, otherwise // treat as a reference pointcut for (Iterator iter = this.pointcutDesignatorHandlers.iterator(); iter.hasNext();) { PointcutDesignatorHandler pcd = (PointcutDesignatorHandler) iter.next(); if (pcd.getDesignatorName().equals(kind)) { p = parseDesignatorPointcut(pcd); matchedByExtensionDesignator = true; } } if (!matchedByExtensionDesignator) { tokenSource.setIndex(start); p = parseReferencePointcut(); } } return p; }
diff --git a/src/com/era7/bioinfo/annotation/embl/ExportEmblFiles.java b/src/com/era7/bioinfo/annotation/embl/ExportEmblFiles.java index 673f648..c96c64b 100644 --- a/src/com/era7/bioinfo/annotation/embl/ExportEmblFiles.java +++ b/src/com/era7/bioinfo/annotation/embl/ExportEmblFiles.java @@ -1,647 +1,647 @@ /* * Copyright (C) 2010-2011 "BG7" * * This file is part of BG7 * * BG7 is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.era7.bioinfo.annotation.embl; import com.era7.lib.bioinfo.bioinfoutil.Executable; import com.era7.lib.bioinfo.bioinfoutil.model.Feature; import com.era7.lib.bioinfoxml.Annotation; import com.era7.lib.bioinfoxml.ContigXML; import com.era7.lib.bioinfoxml.PredictedGene; import com.era7.lib.bioinfoxml.PredictedGenes; import com.era7.lib.bioinfoxml.PredictedRna; import com.era7.lib.bioinfoxml.PredictedRnas; import com.era7.lib.bioinfoxml.embl.EmblXML; import com.era7.lib.era7xmlapi.model.XMLElementException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.jdom.Element; /** * * @author Pablo Pareja Tobes <[email protected]> */ public class ExportEmblFiles implements Executable { public static final int DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES = 3; public static final int LINE_MAX_LENGTH = 80; public static int GENE_AND_RNA_COUNTER = 1; public void execute(ArrayList<String> array) { String[] args = new String[array.size()]; for (int i = 0; i < array.size(); i++) { args[i] = array.get(i); } main(args); } public static void main(String[] args) { if (args.length != 5) { System.out.println("This program expects 5 parameters: \n" + "1. Gene annotation XML result filename \n" + "2. Embl general info XML filename\n" + "3. FNA file with both header and contig sequence\n" + "4. Prefix string for output files\n" + "5. Initial ID value for genes/rnas (integer)"); } else { String annotationFileString = args[0]; String emblXmlFileString = args[1]; String fnaContigFileString = args[2]; String outFileString = args[3]; File annotationFile = new File(annotationFileString); File fnaContigFile = new File(fnaContigFileString); File emblXmlFile = new File(emblXmlFileString); File mainOutFile = new File(outFileString + "MainOutFile.embl"); try { GENE_AND_RNA_COUNTER = Integer.parseInt(args[4]); BufferedWriter mainOutBuff = new BufferedWriter(new FileWriter(mainOutFile)); //-----READING XML FILE WITH ANNOTATION DATA------------ BufferedReader reader = new BufferedReader(new FileReader(annotationFile)); String tempSt; StringBuilder stBuilder = new StringBuilder(); while ((tempSt = reader.readLine()) != null) { stBuilder.append(tempSt); } //Closing file reader.close(); Annotation annotation = new Annotation(stBuilder.toString()); //------------------------------------------------------------- //-----READING XML GENERAL INFO FILE------------ reader = new BufferedReader(new FileReader(emblXmlFile)); stBuilder = new StringBuilder(); while ((tempSt = reader.readLine()) != null) { stBuilder.append(tempSt); } //Closing file reader.close(); EmblXML emblXML = new EmblXML(stBuilder.toString()); //------------------------------------------------------------- //-------------PARSING CONTIGS & THEIR SEQUENCES------------------ HashMap<String, String> contigsMap = new HashMap<String, String>(); reader = new BufferedReader(new FileReader(fnaContigFile)); stBuilder.delete(0, stBuilder.length()); String currentContigId = ""; while ((tempSt = reader.readLine()) != null) { if (tempSt.charAt(0) == '>') { if (stBuilder.length() > 0) { contigsMap.put(currentContigId, stBuilder.toString()); stBuilder.delete(0, stBuilder.length()); } currentContigId = tempSt.substring(1).trim().split(" ")[0].split("\t")[0]; System.out.println("currentContigId = " + currentContigId); } else { stBuilder.append(tempSt); } } if (stBuilder.length() > 0) { contigsMap.put(currentContigId, stBuilder.toString()); } reader.close(); //------------------------------------------------------------- List<Element> contigList = annotation.asJDomElement().getChild(PredictedGenes.TAG_NAME).getChildren(ContigXML.TAG_NAME); List<Element> contigListRna = annotation.asJDomElement().getChild(PredictedRnas.TAG_NAME).getChildren(ContigXML.TAG_NAME); HashMap<String, ContigXML> contigsRnaMap = new HashMap<String, ContigXML>(); for (Element element : contigListRna) { ContigXML rnaContig = new ContigXML(element); contigsRnaMap.put(rnaContig.getId(), rnaContig); } //-----------CONTIGS LOOP----------------------- for (Element elem : contigList) { ContigXML currentContig = new ContigXML(elem); String mainSequence = contigsMap.get(currentContig.getId()); //removing the sequence from the map so that afterwards contigs //with no annotations can be identified contigsMap.remove(currentContig.getId()); exportContigToEmbl(currentContig, emblXML, outFileString, mainSequence, contigsRnaMap, mainOutBuff); } System.out.println("There are " + contigsMap.size() + " contigs with no annotations..."); System.out.println("generating their embl files..."); Set<String> keys = contigsMap.keySet(); for (String tempKey : keys) { System.out.println("generating file for contig: " + tempKey); ContigXML currentContig = new ContigXML(); currentContig.setId(tempKey); String mainSequence = contigsMap.get(currentContig.getId()); exportContigToEmbl(currentContig, emblXML, outFileString, mainSequence, contigsRnaMap, mainOutBuff); } //closing main out file mainOutBuff.close(); System.out.println("Embl files succesfully created! :)"); } catch (Exception e) { e.printStackTrace(); } } } private static void exportContigToEmbl(ContigXML currentContig, EmblXML emblXml, String outFileString, String mainSequence, HashMap<String, ContigXML> contigsRnaMap, BufferedWriter mainOutFileBuff) throws IOException, XMLElementException { File outFile = new File(outFileString + currentContig.getId() + ".embl"); StringBuilder fileStringBuilder = new StringBuilder(); //-------------------------ID line----------------------------------- String idLineSt = ""; idLineSt += "ID" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); //idLineSt += currentContig.getId() + "; " + currentContig.getId() + "; "; - idLineSt += emblXml.getId() + currentContig.getLength() + " BP." + "\n"; + idLineSt += emblXml.getId() + mainSequence.length() + " BP." + "\n"; fileStringBuilder.append(idLineSt); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("DE" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getDefinition() + " " + currentContig.getId() + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("AC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + ";" + "\n")); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("KW" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + "." + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("OS" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getOrganism() + "\n")); String[] lineageSplit = emblXml.getOrganismCompleteTaxonomyLineage().split(";"); String tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); for (String lineageSt : lineageSplit) { if ((tempLineageLine.length() + lineageSt.length() + 1) < LINE_MAX_LENGTH) { tempLineageLine += lineageSt + ";"; } else { fileStringBuilder.append((tempLineageLine + "\n")); if (lineageSt.charAt(0) == ' ') { lineageSt = lineageSt.substring(1); } tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + lineageSt + ";"; } } if (tempLineageLine.length() > 0) { fileStringBuilder.append((tempLineageLine + "\n")); } fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("FH Key Location/Qualifiers" + "\n")); String sourceSt = "FT source "; sourceSt += "1.." + mainSequence.length() + "\n"; fileStringBuilder.append(sourceSt); fileStringBuilder.append(("FT /organism=\"" + emblXml.getOrganism() + "\"" + "\n")); fileStringBuilder.append(("FT /mol_type=\"" + emblXml.getMolType() + "\"" + "\n")); fileStringBuilder.append(("FT /strain=\"" + emblXml.getStrain() + "\"" + "\n")); //------Hashmap with key = gene/rna id and the value = //---- respective String exactly as is must be written to the result file--------------------------- HashMap<String, String> genesRnasMixedUpMap = new HashMap<String, String>(); TreeSet<Feature> featuresTreeSet = new TreeSet<Feature>(); //----------------------GENES LOOP---------------------------- List<Element> genesList = currentContig.asJDomElement().getChildren(PredictedGene.TAG_NAME); for (Element element : genesList) { PredictedGene gene = new PredictedGene(element); Feature tempFeature = new Feature(); tempFeature.setId(gene.getId()); if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(gene.getStartPosition()); tempFeature.setEnd(gene.getEndPosition()); } else { tempFeature.setBegin(gene.getEndPosition()); tempFeature.setEnd(gene.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(gene.getId(), getGeneStringForEmbl(gene,emblXml.getLocusTagPrefix())); } //-------------------------------------------------------------- //Now rnas are added (if there are any) so that everything can be sort afterwards ContigXML contig = contigsRnaMap.get(currentContig.getId()); if (contig != null) { List<Element> rnas = contig.asJDomElement().getChildren(PredictedRna.TAG_NAME); for (Element tempElem : rnas) { PredictedRna rna = new PredictedRna(tempElem); Feature tempFeature = new Feature(); tempFeature.setId(rna.getId()); if (rna.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(rna.getStartPosition()); tempFeature.setEnd(rna.getEndPosition()); } else { tempFeature.setBegin(rna.getEndPosition()); tempFeature.setEnd(rna.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(rna.getId(), getRnaStringForEmbl(rna, emblXml.getLocusTagPrefix())); } } //Once genes & rnas are sorted, we just have to write them for (Feature f : featuresTreeSet) { fileStringBuilder.append(genesRnasMixedUpMap.get(f.getId())); } //--------------ORIGIN----------------------------------------- fileStringBuilder.append(("SQ Sequence " + mainSequence.length() + " BP;" + "\n")); int maxDigits = 10; int positionCounter = 1; int maxBasesPerLine = 60; int currentBase = 0; int seqFragmentLength = 10; // System.out.println("currentContig.getId() = " + currentContig.getId()); // System.out.println("mainSequence.length() = " + mainSequence.length()); // System.out.println(contigsMap.get(currentContig.getId()).length()); for (currentBase = 0; (currentBase + maxBasesPerLine) < mainSequence.length(); positionCounter += maxBasesPerLine) { String tempLine = getWhiteSpaces(5); for (int i = 1; i <= (maxBasesPerLine / seqFragmentLength); i++) { tempLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); currentBase += seqFragmentLength; } String posSt = String.valueOf(positionCounter - 1 + maxBasesPerLine); tempLine += getWhiteSpaces(maxDigits - posSt.length()) + posSt; fileStringBuilder.append((tempLine + "\n")); } if (currentBase < mainSequence.length()) { String lastLine = getWhiteSpaces(5); while (currentBase < mainSequence.length()) { if ((currentBase + seqFragmentLength) < mainSequence.length()) { lastLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); } else { lastLine += " " + mainSequence.substring(currentBase, mainSequence.length()); } currentBase += seqFragmentLength; } String posSt = String.valueOf(mainSequence.length()); lastLine += getWhiteSpaces(LINE_MAX_LENGTH - posSt.length() - lastLine.length() + 1) + posSt; fileStringBuilder.append((lastLine + "\n")); } //-------------------------------------------------------------- //--- finally I have to add the string "//" in the last line-- fileStringBuilder.append("//\n"); BufferedWriter outBuff = new BufferedWriter(new FileWriter(outFile)); outBuff.write(fileStringBuilder.toString()); outBuff.close(); mainOutFileBuff.write(fileStringBuilder.toString()); mainOutFileBuff.flush(); } private static String getWhiteSpaces(int number) { String result = ""; for (int i = 0; i < number; i++) { result += " "; } return result; } private static String patatizaEnLineas(String header, String value, int numberOfWhiteSpacesForIndentation, boolean putQuotationMarksInTheEnd) { //value = value.toUpperCase(); String result = ""; result += header; int lengthWithoutIndentation = LINE_MAX_LENGTH - numberOfWhiteSpacesForIndentation - 2; if (value.length() < (LINE_MAX_LENGTH - header.length())) { result += value; if (putQuotationMarksInTheEnd) { result += "\""; } result += "\n"; } else if (value.length() == (LINE_MAX_LENGTH - header.length())) { result += value + "\n"; if (putQuotationMarksInTheEnd) { result += "FT" + getWhiteSpaces(numberOfWhiteSpacesForIndentation) + "\"\n"; } } else { result += value.substring(0, (LINE_MAX_LENGTH - header.length())) + "\n"; value = value.substring((LINE_MAX_LENGTH - header.length()), value.length()); while (value.length() > lengthWithoutIndentation) { result += "FT" + getWhiteSpaces(numberOfWhiteSpacesForIndentation) + value.substring(0, lengthWithoutIndentation) + "\n"; value = value.substring(lengthWithoutIndentation, value.length()); } if (value.length() == lengthWithoutIndentation) { result += "FT" + getWhiteSpaces(numberOfWhiteSpacesForIndentation) + value + "\n"; if (putQuotationMarksInTheEnd) { result += "FT" + getWhiteSpaces(numberOfWhiteSpacesForIndentation) + "\"\n"; } } else { result += "FT" + getWhiteSpaces(numberOfWhiteSpacesForIndentation) + value; if (putQuotationMarksInTheEnd) { result += "\""; } result += "\n"; } } return result; } private static String getGeneStringForEmbl(PredictedGene gene, String locusTagPrefix) throws XMLElementException { StringBuilder geneStBuilder = new StringBuilder(); boolean negativeStrand = gene.getStrand().equals(PredictedGene.NEGATIVE_STRAND); String genePositionsString = ""; String cdsPositionsString = ""; if (negativeStrand) { genePositionsString += "complement("; if (!gene.getEndIsCanonical()) { genePositionsString += "<"; } cdsPositionsString = genePositionsString; genePositionsString += gene.getEndPosition() + ".."; if (gene.getEndPosition() > 4) { cdsPositionsString += (gene.getEndPosition() - 3) + ".."; } else { cdsPositionsString = genePositionsString; } if (!gene.getStartIsCanonical()) { genePositionsString += ">"; cdsPositionsString += ">"; } genePositionsString += gene.getStartPosition() + ")"; cdsPositionsString += gene.getStartPosition() + ")"; } else { if (!gene.getStartIsCanonical()) { genePositionsString += "<"; } genePositionsString += gene.getStartPosition() + ".."; if (!gene.getEndIsCanonical()) { genePositionsString += ">"; } cdsPositionsString = genePositionsString; genePositionsString += gene.getEndPosition(); cdsPositionsString += gene.getEndPosition() + 3; } //gene part // String tempGeneStr = "FT " // + "gene" // + getWhiteSpaces(12) // + genePositionsString + "\n"; // // geneStBuilder.append(tempGeneStr); // geneStBuilder.append(patatizaEnLineas("FT" // + getWhiteSpaces(19) + "/product=\"", // gene.getProteinNames(), // 19, // true)); // // geneStBuilder.append(patatizaEnLineas("FT" // + getWhiteSpaces(19) + "/locus_tag=\"", // getLocusTagNumberAsText(locusTagPrefix, GENE_AND_RNA_COUNTER), // 19, // true)); // // GENE_AND_RNA_COUNTER++; String tempCDSString = "FT" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + "CDS" + getWhiteSpaces(13); tempCDSString += cdsPositionsString + "\n"; geneStBuilder.append(tempCDSString); geneStBuilder.append(patatizaEnLineas("FT" + getWhiteSpaces(19) + "/locus_tag=\"", getLocusTagNumberAsText(locusTagPrefix, GENE_AND_RNA_COUNTER), 19, true)); GENE_AND_RNA_COUNTER++; geneStBuilder.append(patatizaEnLineas("FT" + getWhiteSpaces(19) + "/product=\"", gene.getProteinNames(), 19, true)); if(!gene.getEndIsCanonical() || !gene.getStartIsCanonical() || (gene.getFrameshifts() != null) || (gene.getExtraStopCodons() != null)){ geneStBuilder.append(("FT" + getWhiteSpaces(19) + "/pseudo" + "\n")); } if (gene.getProteinSequence() != null) { if (!gene.getProteinSequence().equals("")) { boolean includeSequence = gene.getEndIsCanonical() && gene.getStartIsCanonical() && (gene.getExtraStopCodons() == null) && (gene.getFrameshifts() == null); if (includeSequence) { String protSeq = gene.getProteinSequence(); if (!protSeq.substring(0, 1).toUpperCase().equals("M")) { protSeq = "M" + protSeq.substring(1); } geneStBuilder.append(patatizaEnLineas("FT" + getWhiteSpaces(19) + "/translation=\"", protSeq, 19, true)); } } } return geneStBuilder.toString(); } private static String getRnaStringForEmbl(PredictedRna rna, String locusTagPrefix) { StringBuilder rnaStBuilder = new StringBuilder(); boolean negativeStrand = rna.getStrand().equals(PredictedRna.NEGATIVE_STRAND); String positionsString = ""; if (negativeStrand) { positionsString += "complement("; // if (!rna.getEndIsCanonical()) { // positionsString += "<"; // } positionsString += "<" + rna.getEndPosition() + ".." + ">" + rna.getStartPosition(); // if (!rna.getStartIsCanonical()) { // positionsString += ">"; // } positionsString += ")"; } else { // if (!rna.getStartIsCanonical()) { // positionsString += "<"; // } positionsString += "<" + rna.getStartPosition() + ".." + ">" + rna.getEndPosition(); // if (!rna.getEndIsCanonical()) { // positionsString += ">"; // } } //rna part // String tempRnaStr = "FT " // + "gene" // + getWhiteSpaces(12) // + positionsString + "\n"; // // rnaStBuilder.append(tempRnaStr); // rnaStBuilder.append(patatizaEnLineas("FT" // + getWhiteSpaces(19) + "/product=\"", // rna.getAnnotationUniprotId().split("\\|")[3], // 19, // true)); //System.out.println("rna.getId() = " + rna.getId()); //System.out.println("rna.getAnnotationUniprotId() = " + rna.getAnnotationUniprotId()); String rnaProduct = rna.getAnnotationUniprotId().split("\\|")[3]; String rnaValue = "rna"; if(rnaProduct.toLowerCase().contains("ribosomal")){ rnaValue = "rRNA"; }else if(rnaProduct.toLowerCase().contains("trna")){ rnaValue = "tRNA"; } String tempRNAString = "FT " + rnaValue + getWhiteSpaces(13); tempRNAString += positionsString + "\n"; rnaStBuilder.append(tempRNAString); rnaStBuilder.append(patatizaEnLineas("FT" + getWhiteSpaces(19) + "/locus_tag=\"", getLocusTagNumberAsText(locusTagPrefix, GENE_AND_RNA_COUNTER), 19, true)); GENE_AND_RNA_COUNTER++; rnaStBuilder.append(patatizaEnLineas("FT" + getWhiteSpaces(19) + "/product=\"", rnaProduct, 19, true)); return rnaStBuilder.toString(); } private static String getLocusTagNumberAsText(String prefix, int number){ String numberSt = String.valueOf(number); String result = prefix; for (int i = 0; i < (5 - numberSt.length()); i++) { result += "0"; } return (result + numberSt); } }
true
true
private static void exportContigToEmbl(ContigXML currentContig, EmblXML emblXml, String outFileString, String mainSequence, HashMap<String, ContigXML> contigsRnaMap, BufferedWriter mainOutFileBuff) throws IOException, XMLElementException { File outFile = new File(outFileString + currentContig.getId() + ".embl"); StringBuilder fileStringBuilder = new StringBuilder(); //-------------------------ID line----------------------------------- String idLineSt = ""; idLineSt += "ID" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); //idLineSt += currentContig.getId() + "; " + currentContig.getId() + "; "; idLineSt += emblXml.getId() + currentContig.getLength() + " BP." + "\n"; fileStringBuilder.append(idLineSt); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("DE" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getDefinition() + " " + currentContig.getId() + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("AC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + ";" + "\n")); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("KW" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + "." + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("OS" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getOrganism() + "\n")); String[] lineageSplit = emblXml.getOrganismCompleteTaxonomyLineage().split(";"); String tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); for (String lineageSt : lineageSplit) { if ((tempLineageLine.length() + lineageSt.length() + 1) < LINE_MAX_LENGTH) { tempLineageLine += lineageSt + ";"; } else { fileStringBuilder.append((tempLineageLine + "\n")); if (lineageSt.charAt(0) == ' ') { lineageSt = lineageSt.substring(1); } tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + lineageSt + ";"; } } if (tempLineageLine.length() > 0) { fileStringBuilder.append((tempLineageLine + "\n")); } fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("FH Key Location/Qualifiers" + "\n")); String sourceSt = "FT source "; sourceSt += "1.." + mainSequence.length() + "\n"; fileStringBuilder.append(sourceSt); fileStringBuilder.append(("FT /organism=\"" + emblXml.getOrganism() + "\"" + "\n")); fileStringBuilder.append(("FT /mol_type=\"" + emblXml.getMolType() + "\"" + "\n")); fileStringBuilder.append(("FT /strain=\"" + emblXml.getStrain() + "\"" + "\n")); //------Hashmap with key = gene/rna id and the value = //---- respective String exactly as is must be written to the result file--------------------------- HashMap<String, String> genesRnasMixedUpMap = new HashMap<String, String>(); TreeSet<Feature> featuresTreeSet = new TreeSet<Feature>(); //----------------------GENES LOOP---------------------------- List<Element> genesList = currentContig.asJDomElement().getChildren(PredictedGene.TAG_NAME); for (Element element : genesList) { PredictedGene gene = new PredictedGene(element); Feature tempFeature = new Feature(); tempFeature.setId(gene.getId()); if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(gene.getStartPosition()); tempFeature.setEnd(gene.getEndPosition()); } else { tempFeature.setBegin(gene.getEndPosition()); tempFeature.setEnd(gene.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(gene.getId(), getGeneStringForEmbl(gene,emblXml.getLocusTagPrefix())); } //-------------------------------------------------------------- //Now rnas are added (if there are any) so that everything can be sort afterwards ContigXML contig = contigsRnaMap.get(currentContig.getId()); if (contig != null) { List<Element> rnas = contig.asJDomElement().getChildren(PredictedRna.TAG_NAME); for (Element tempElem : rnas) { PredictedRna rna = new PredictedRna(tempElem); Feature tempFeature = new Feature(); tempFeature.setId(rna.getId()); if (rna.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(rna.getStartPosition()); tempFeature.setEnd(rna.getEndPosition()); } else { tempFeature.setBegin(rna.getEndPosition()); tempFeature.setEnd(rna.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(rna.getId(), getRnaStringForEmbl(rna, emblXml.getLocusTagPrefix())); } } //Once genes & rnas are sorted, we just have to write them for (Feature f : featuresTreeSet) { fileStringBuilder.append(genesRnasMixedUpMap.get(f.getId())); } //--------------ORIGIN----------------------------------------- fileStringBuilder.append(("SQ Sequence " + mainSequence.length() + " BP;" + "\n")); int maxDigits = 10; int positionCounter = 1; int maxBasesPerLine = 60; int currentBase = 0; int seqFragmentLength = 10; // System.out.println("currentContig.getId() = " + currentContig.getId()); // System.out.println("mainSequence.length() = " + mainSequence.length()); // System.out.println(contigsMap.get(currentContig.getId()).length()); for (currentBase = 0; (currentBase + maxBasesPerLine) < mainSequence.length(); positionCounter += maxBasesPerLine) { String tempLine = getWhiteSpaces(5); for (int i = 1; i <= (maxBasesPerLine / seqFragmentLength); i++) { tempLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); currentBase += seqFragmentLength; } String posSt = String.valueOf(positionCounter - 1 + maxBasesPerLine); tempLine += getWhiteSpaces(maxDigits - posSt.length()) + posSt; fileStringBuilder.append((tempLine + "\n")); } if (currentBase < mainSequence.length()) { String lastLine = getWhiteSpaces(5); while (currentBase < mainSequence.length()) { if ((currentBase + seqFragmentLength) < mainSequence.length()) { lastLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); } else { lastLine += " " + mainSequence.substring(currentBase, mainSequence.length()); } currentBase += seqFragmentLength; } String posSt = String.valueOf(mainSequence.length()); lastLine += getWhiteSpaces(LINE_MAX_LENGTH - posSt.length() - lastLine.length() + 1) + posSt; fileStringBuilder.append((lastLine + "\n")); } //-------------------------------------------------------------- //--- finally I have to add the string "//" in the last line-- fileStringBuilder.append("//\n"); BufferedWriter outBuff = new BufferedWriter(new FileWriter(outFile)); outBuff.write(fileStringBuilder.toString()); outBuff.close(); mainOutFileBuff.write(fileStringBuilder.toString()); mainOutFileBuff.flush(); }
private static void exportContigToEmbl(ContigXML currentContig, EmblXML emblXml, String outFileString, String mainSequence, HashMap<String, ContigXML> contigsRnaMap, BufferedWriter mainOutFileBuff) throws IOException, XMLElementException { File outFile = new File(outFileString + currentContig.getId() + ".embl"); StringBuilder fileStringBuilder = new StringBuilder(); //-------------------------ID line----------------------------------- String idLineSt = ""; idLineSt += "ID" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); //idLineSt += currentContig.getId() + "; " + currentContig.getId() + "; "; idLineSt += emblXml.getId() + mainSequence.length() + " BP." + "\n"; fileStringBuilder.append(idLineSt); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("DE" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getDefinition() + " " + currentContig.getId() + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("AC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + ";" + "\n")); fileStringBuilder.append("XX" + "\n"); fileStringBuilder.append(("KW" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + "." + "\n")); fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("OS" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + emblXml.getOrganism() + "\n")); String[] lineageSplit = emblXml.getOrganismCompleteTaxonomyLineage().split(";"); String tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES); for (String lineageSt : lineageSplit) { if ((tempLineageLine.length() + lineageSt.length() + 1) < LINE_MAX_LENGTH) { tempLineageLine += lineageSt + ";"; } else { fileStringBuilder.append((tempLineageLine + "\n")); if (lineageSt.charAt(0) == ' ') { lineageSt = lineageSt.substring(1); } tempLineageLine = "OC" + getWhiteSpaces(DEFAULT_INDENTATION_NUMBER_OF_WHITESPACES) + lineageSt + ";"; } } if (tempLineageLine.length() > 0) { fileStringBuilder.append((tempLineageLine + "\n")); } fileStringBuilder.append(("XX" + "\n")); fileStringBuilder.append(("FH Key Location/Qualifiers" + "\n")); String sourceSt = "FT source "; sourceSt += "1.." + mainSequence.length() + "\n"; fileStringBuilder.append(sourceSt); fileStringBuilder.append(("FT /organism=\"" + emblXml.getOrganism() + "\"" + "\n")); fileStringBuilder.append(("FT /mol_type=\"" + emblXml.getMolType() + "\"" + "\n")); fileStringBuilder.append(("FT /strain=\"" + emblXml.getStrain() + "\"" + "\n")); //------Hashmap with key = gene/rna id and the value = //---- respective String exactly as is must be written to the result file--------------------------- HashMap<String, String> genesRnasMixedUpMap = new HashMap<String, String>(); TreeSet<Feature> featuresTreeSet = new TreeSet<Feature>(); //----------------------GENES LOOP---------------------------- List<Element> genesList = currentContig.asJDomElement().getChildren(PredictedGene.TAG_NAME); for (Element element : genesList) { PredictedGene gene = new PredictedGene(element); Feature tempFeature = new Feature(); tempFeature.setId(gene.getId()); if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(gene.getStartPosition()); tempFeature.setEnd(gene.getEndPosition()); } else { tempFeature.setBegin(gene.getEndPosition()); tempFeature.setEnd(gene.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(gene.getId(), getGeneStringForEmbl(gene,emblXml.getLocusTagPrefix())); } //-------------------------------------------------------------- //Now rnas are added (if there are any) so that everything can be sort afterwards ContigXML contig = contigsRnaMap.get(currentContig.getId()); if (contig != null) { List<Element> rnas = contig.asJDomElement().getChildren(PredictedRna.TAG_NAME); for (Element tempElem : rnas) { PredictedRna rna = new PredictedRna(tempElem); Feature tempFeature = new Feature(); tempFeature.setId(rna.getId()); if (rna.getStrand().equals(PredictedGene.POSITIVE_STRAND)) { tempFeature.setBegin(rna.getStartPosition()); tempFeature.setEnd(rna.getEndPosition()); } else { tempFeature.setBegin(rna.getEndPosition()); tempFeature.setEnd(rna.getStartPosition()); } featuresTreeSet.add(tempFeature); genesRnasMixedUpMap.put(rna.getId(), getRnaStringForEmbl(rna, emblXml.getLocusTagPrefix())); } } //Once genes & rnas are sorted, we just have to write them for (Feature f : featuresTreeSet) { fileStringBuilder.append(genesRnasMixedUpMap.get(f.getId())); } //--------------ORIGIN----------------------------------------- fileStringBuilder.append(("SQ Sequence " + mainSequence.length() + " BP;" + "\n")); int maxDigits = 10; int positionCounter = 1; int maxBasesPerLine = 60; int currentBase = 0; int seqFragmentLength = 10; // System.out.println("currentContig.getId() = " + currentContig.getId()); // System.out.println("mainSequence.length() = " + mainSequence.length()); // System.out.println(contigsMap.get(currentContig.getId()).length()); for (currentBase = 0; (currentBase + maxBasesPerLine) < mainSequence.length(); positionCounter += maxBasesPerLine) { String tempLine = getWhiteSpaces(5); for (int i = 1; i <= (maxBasesPerLine / seqFragmentLength); i++) { tempLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); currentBase += seqFragmentLength; } String posSt = String.valueOf(positionCounter - 1 + maxBasesPerLine); tempLine += getWhiteSpaces(maxDigits - posSt.length()) + posSt; fileStringBuilder.append((tempLine + "\n")); } if (currentBase < mainSequence.length()) { String lastLine = getWhiteSpaces(5); while (currentBase < mainSequence.length()) { if ((currentBase + seqFragmentLength) < mainSequence.length()) { lastLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength); } else { lastLine += " " + mainSequence.substring(currentBase, mainSequence.length()); } currentBase += seqFragmentLength; } String posSt = String.valueOf(mainSequence.length()); lastLine += getWhiteSpaces(LINE_MAX_LENGTH - posSt.length() - lastLine.length() + 1) + posSt; fileStringBuilder.append((lastLine + "\n")); } //-------------------------------------------------------------- //--- finally I have to add the string "//" in the last line-- fileStringBuilder.append("//\n"); BufferedWriter outBuff = new BufferedWriter(new FileWriter(outFile)); outBuff.write(fileStringBuilder.toString()); outBuff.close(); mainOutFileBuff.write(fileStringBuilder.toString()); mainOutFileBuff.flush(); }
diff --git a/components/messaging/messaging-core/src/main/java/org/torquebox/messaging/core/RubyMessageProcessor.java b/components/messaging/messaging-core/src/main/java/org/torquebox/messaging/core/RubyMessageProcessor.java index 4d0bbd58a..324bbc096 100644 --- a/components/messaging/messaging-core/src/main/java/org/torquebox/messaging/core/RubyMessageProcessor.java +++ b/components/messaging/messaging-core/src/main/java/org/torquebox/messaging/core/RubyMessageProcessor.java @@ -1,252 +1,253 @@ /* * Copyright 2008-2011 Red Hat, Inc, and individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.torquebox.messaging.core; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.Topic; import org.jboss.logging.Logger; import org.jruby.Ruby; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; import org.torquebox.interp.core.RubyComponentResolver; import org.torquebox.interp.spi.RubyRuntimePool; public class RubyMessageProcessor implements RubyMessageProcessorMBean { @SuppressWarnings("unused") private static final Logger log = Logger.getLogger( RubyMessageProcessor.class ); public RubyMessageProcessor() { } public String toString() { return "[RubyMessageProcessor: " + getName() + "]"; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setComponentResolver(RubyComponentResolver resolver) { this.componentResolver = resolver; } public RubyComponentResolver getComponentResolver() { return this.componentResolver; } public void setDestination(Destination destination) { this.destination = destination; } public Destination getDestination() { return this.destination; } public String getDestinationName() { return this.destination.toString(); } public void setMessageSelector(String messageSelector) { this.messageSelector = messageSelector; } public String getMessageSelector() { return this.messageSelector; } public void setAcknowledgeMode(int acknowledgeMode) { this.acknowledgeMode = acknowledgeMode; } public int getAcknowledgeMode() { return this.acknowledgeMode; } public void setConnectionFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public ConnectionFactory getConnectionFactory() { return this.connectionFactory; } public void setRubyRuntimePool(RubyRuntimePool rubyRuntimePool) { this.rubyRuntimePool = rubyRuntimePool; } public RubyRuntimePool getRubyRuntimePool() { return this.rubyRuntimePool; } public void setConcurrency(int concurrency) { this.concurrency = concurrency; } public int getConcurrency() { return this.concurrency; } // Durability only has meaning for topic processors, not for queues public void setDurable(boolean durable) { this.durable = durable; } public boolean getDurable() { return this.durable; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return this.applicationName; } public void create() throws JMSException { if (getConcurrency() > 1 && getDestination() instanceof Topic) { log.warn( "Creating " + this.toString() + " for a Topic with a " + "concurrency greater than 1. This will result in " + "duplicate messages being processed and is an uncommon " + "usage of Topic MessageProcessors."); } this.connection = this.connectionFactory.createConnection(); this.connection.setClientID( getApplicationName() ); for (int i = 0; i < getConcurrency(); i++) { new Handler( this.connection.createSession( true, this.acknowledgeMode ) ); } } public void start() throws JMSException { if (connection != null) { connection.start(); this.started = true; } } public void stop() throws JMSException { if (this.connection != null) { this.connection.stop(); this.started = false; } } public void destroy() throws JMSException { if (this.connection != null) { this.connection.close(); this.connection = null; } } public synchronized String getStatus() { if ( this.started ) { return "STARTED"; } return "STOPPED"; } protected IRubyObject instantiateProcessor(Ruby ruby) throws Exception { return this.componentResolver.resolve( ruby ); } protected void processMessage(IRubyObject processor, Message message) { Ruby ruby = processor.getRuntime(); JavaEmbedUtils.invokeMethod( ruby, processor, "process!", new Object[] { message }, void.class ); } class Handler implements MessageListener { Handler(Session session) throws JMSException { MessageConsumer consumer = null; if (getDurable() && getDestination() instanceof Topic) { consumer = session.createDurableSubscriber( (Topic)getDestination(), getName(), getMessageSelector(), false ); } else { if (getDurable() && !(getDestination() instanceof Topic)) { log.warn( "Durable set for processor " + getName() + ", but " + getDestinationName() + " is not a topic - ignoring." ); } consumer = session.createConsumer( getDestination(), getMessageSelector() ); } consumer.setMessageListener( this ); this.session = session; } public void onMessage(Message message) { Ruby ruby = null; try { ruby = getRubyRuntimePool().borrowRuntime(); IRubyObject processor = instantiateProcessor( ruby ); processMessage( processor, message ); if (session.getTransacted()) { session.commit(); } } catch (Exception e) { + log.error( "Unexpected error in "+getName(), e ); try { if (session.getTransacted()) { session.rollback(); } } catch (JMSException ignored) { } } finally { if (ruby != null) { getRubyRuntimePool().returnRuntime( ruby ); } } } private Session session; } private String name; private Destination destination; private String messageSelector; private ConnectionFactory connectionFactory; private RubyRuntimePool rubyRuntimePool; private Connection connection; private RubyComponentResolver componentResolver; private int concurrency = 1; private boolean started = false; private boolean durable = false; private String applicationName; private int acknowledgeMode = Session.AUTO_ACKNOWLEDGE; }
true
true
public void onMessage(Message message) { Ruby ruby = null; try { ruby = getRubyRuntimePool().borrowRuntime(); IRubyObject processor = instantiateProcessor( ruby ); processMessage( processor, message ); if (session.getTransacted()) { session.commit(); } } catch (Exception e) { try { if (session.getTransacted()) { session.rollback(); } } catch (JMSException ignored) { } } finally { if (ruby != null) { getRubyRuntimePool().returnRuntime( ruby ); } } }
public void onMessage(Message message) { Ruby ruby = null; try { ruby = getRubyRuntimePool().borrowRuntime(); IRubyObject processor = instantiateProcessor( ruby ); processMessage( processor, message ); if (session.getTransacted()) { session.commit(); } } catch (Exception e) { log.error( "Unexpected error in "+getName(), e ); try { if (session.getTransacted()) { session.rollback(); } } catch (JMSException ignored) { } } finally { if (ruby != null) { getRubyRuntimePool().returnRuntime( ruby ); } } }
diff --git a/src/com/dalthed/tucan/scraper/ScheduleScraper.java b/src/com/dalthed/tucan/scraper/ScheduleScraper.java index 2575147..2cdb3dc 100644 --- a/src/com/dalthed/tucan/scraper/ScheduleScraper.java +++ b/src/com/dalthed/tucan/scraper/ScheduleScraper.java @@ -1,173 +1,173 @@ /** * This file is part of TuCan Mobile. * * TuCan Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TuCan Mobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.scraper; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import org.jsoup.nodes.Element; import android.content.Context; import android.widget.ListAdapter; import com.dalthed.tucan.R; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.BrowserAnswerReciever; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.Connection.RequestObject; import com.dalthed.tucan.Connection.SimpleSecureBrowser; import com.dalthed.tucan.adapters.ScheduleAdapter; import com.dalthed.tucan.exceptions.LostSessionException; import com.dalthed.tucan.exceptions.TucanDownException; public class ScheduleScraper extends BasicScraper { public ArrayList<String> eventLink, eventDay, eventTime, eventRoom, eventName; public ArrayList<Boolean> firstEventofDay; private CookieManager localCookieManager; private int step = 0; public ScheduleScraper(Context context, AnswerObject result) { super(context, result); localCookieManager = result.getCookieManager(); } @Override public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { if (checkForLostSeesion()) { Iterator<Element> schedDays = doc.select("div.tbMonthDay").iterator(); int Month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH); int Day = java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH); int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR); if (step == 0) { loadNextPage(); } if (step == 1) { if(Month==12) { Month=1; }else { Month++; } } scrapeDates(step, schedDays, Month, Day,year); if (step == 1) { ScheduleAdapter externAdapter = new ScheduleAdapter(context, eventDay, eventTime, firstEventofDay, eventRoom, eventName); return externAdapter; } else { step = 1; } } return null; } /** * @param mode * @param schedDays * @param month * @param day */ private void scrapeDates(int step, Iterator<Element> schedDays, int month, int day,int year) { SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); while (schedDays.hasNext()) { Element next = schedDays.next(); String monthday = next.attr("title"); Iterator<Element> dayEvents = next.select("div.appMonth").iterator(); if (dayEvents != null) { int i = 0; while (dayEvents.hasNext()) { Element nextEvent = dayEvents.next(); if (Integer.parseInt(monthday.trim()) >= day || step == 1) { String[] LinktitleArgument = nextEvent.select("a").attr("title") .split(" / "); if (i == 0) { firstEventofDay.add(true); } else { firstEventofDay.add(false); } i++; StringBuilder displayDate = new StringBuilder(); if (Integer.parseInt(monthday.trim()) == day && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_today)); } else if (Integer.parseInt(monthday.trim()) == (day + 1) && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_tomorrow)); } else { - displayDate.append(monthday).append(".").append((month + 1)); + displayDate.append(monthday).append(".").append((month % 12 + 1)); } String weekday = sdf.format(new Date(year-1900, month, Integer.parseInt(monthday.trim()))); displayDate.append(" - ").append(weekday); eventDay.add(displayDate.toString()); eventTime.add(LinktitleArgument[0].trim()); eventRoom.add(LinktitleArgument[1].trim()); if (LinktitleArgument.length > 2) { eventName.add(LinktitleArgument[2].trim()); } else { eventName.add(""); } eventLink.add(nextEvent.select("a").attr("href")); } } } } } /** * */ private void loadNextPage() { eventDay = new ArrayList<String>(); eventTime = new ArrayList<String>(); eventRoom = new ArrayList<String>(); eventName = new ArrayList<String>(); eventLink = new ArrayList<String>(); firstEventofDay = new ArrayList<Boolean>(); String nextLink = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("a[name=skipForward_btn]").attr("href"); if (context instanceof BrowserAnswerReciever) { SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser( (BrowserAnswerReciever) context); RequestObject thisRequest = new RequestObject(nextLink, localCookieManager, RequestObject.METHOD_GET, ""); callOverviewBrowser.execute(thisRequest); } } }
true
true
private void scrapeDates(int step, Iterator<Element> schedDays, int month, int day,int year) { SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); while (schedDays.hasNext()) { Element next = schedDays.next(); String monthday = next.attr("title"); Iterator<Element> dayEvents = next.select("div.appMonth").iterator(); if (dayEvents != null) { int i = 0; while (dayEvents.hasNext()) { Element nextEvent = dayEvents.next(); if (Integer.parseInt(monthday.trim()) >= day || step == 1) { String[] LinktitleArgument = nextEvent.select("a").attr("title") .split(" / "); if (i == 0) { firstEventofDay.add(true); } else { firstEventofDay.add(false); } i++; StringBuilder displayDate = new StringBuilder(); if (Integer.parseInt(monthday.trim()) == day && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_today)); } else if (Integer.parseInt(monthday.trim()) == (day + 1) && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_tomorrow)); } else { displayDate.append(monthday).append(".").append((month + 1)); } String weekday = sdf.format(new Date(year-1900, month, Integer.parseInt(monthday.trim()))); displayDate.append(" - ").append(weekday); eventDay.add(displayDate.toString()); eventTime.add(LinktitleArgument[0].trim()); eventRoom.add(LinktitleArgument[1].trim()); if (LinktitleArgument.length > 2) { eventName.add(LinktitleArgument[2].trim()); } else { eventName.add(""); } eventLink.add(nextEvent.select("a").attr("href")); } } } } }
private void scrapeDates(int step, Iterator<Element> schedDays, int month, int day,int year) { SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); while (schedDays.hasNext()) { Element next = schedDays.next(); String monthday = next.attr("title"); Iterator<Element> dayEvents = next.select("div.appMonth").iterator(); if (dayEvents != null) { int i = 0; while (dayEvents.hasNext()) { Element nextEvent = dayEvents.next(); if (Integer.parseInt(monthday.trim()) >= day || step == 1) { String[] LinktitleArgument = nextEvent.select("a").attr("title") .split(" / "); if (i == 0) { firstEventofDay.add(true); } else { firstEventofDay.add(false); } i++; StringBuilder displayDate = new StringBuilder(); if (Integer.parseInt(monthday.trim()) == day && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_today)); } else if (Integer.parseInt(monthday.trim()) == (day + 1) && step == 0) { displayDate.append(context.getResources().getString(R.string.schedule_tomorrow)); } else { displayDate.append(monthday).append(".").append((month % 12 + 1)); } String weekday = sdf.format(new Date(year-1900, month, Integer.parseInt(monthday.trim()))); displayDate.append(" - ").append(weekday); eventDay.add(displayDate.toString()); eventTime.add(LinktitleArgument[0].trim()); eventRoom.add(LinktitleArgument[1].trim()); if (LinktitleArgument.length > 2) { eventName.add(LinktitleArgument[2].trim()); } else { eventName.add(""); } eventLink.add(nextEvent.select("a").attr("href")); } } } } }
diff --git a/src/com/mpower/controller/QueryLookupController.java b/src/com/mpower/controller/QueryLookupController.java index c09d255f..cc103b96 100644 --- a/src/com/mpower/controller/QueryLookupController.java +++ b/src/com/mpower/controller/QueryLookupController.java @@ -1,75 +1,75 @@ package com.mpower.controller; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.support.PagedListHolder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.mpower.domain.QueryLookup; import com.mpower.service.QueryLookupService; import com.mpower.service.SessionServiceImpl; public class QueryLookupController implements Controller { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog(getClass()); private QueryLookupService queryLookupService; public void setQueryLookupService(QueryLookupService queryLookupService) { this.queryLookupService = queryLookupService; } @SuppressWarnings("unchecked") @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String param = enu.nextElement(); String paramValue = StringUtils.trimToNull(request.getParameter(param)); - if (paramValue != null && !param.equalsIgnoreCase("fieldDef") && !param.equalsIgnoreCase("view")) { + if (paramValue != null && !param.equalsIgnoreCase("fieldDef") && !param.equalsIgnoreCase("view") && !param.equalsIgnoreCase("resultsOnly")) { queryParams.put(param, paramValue); } } // List<String> displayColumns = new ArrayList<String>(); // displayColumns.add("lastName"); // displayColumns.add("firstName"); String fieldDef = StringUtils.trimToNull(request.getParameter("fieldDef")); QueryLookup queryLookup = queryLookupService.readQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef); List<Object> objects = queryLookupService.executeQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef, queryParams); ModelAndView mav = new ModelAndView("queryLookup"); mav.addObject("objects", objects); PagedListHolder pagedListHolder = new PagedListHolder(objects); pagedListHolder.setMaxLinkedPages(3); pagedListHolder.setPageSize(50); String page = request.getParameter("page"); Integer pg = 0; if (!StringUtils.isBlank(page)) { pg = Integer.valueOf(page); } pagedListHolder.setPage(pg); mav.addObject("pagedListHolder", pagedListHolder); mav.addObject("queryLookup", queryLookup); // mav.addObject("displayColumns", displayColumns); // mav.addObject("parameterMap", request.getParameterMap()); return mav; } }
true
true
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String param = enu.nextElement(); String paramValue = StringUtils.trimToNull(request.getParameter(param)); if (paramValue != null && !param.equalsIgnoreCase("fieldDef") && !param.equalsIgnoreCase("view")) { queryParams.put(param, paramValue); } } // List<String> displayColumns = new ArrayList<String>(); // displayColumns.add("lastName"); // displayColumns.add("firstName"); String fieldDef = StringUtils.trimToNull(request.getParameter("fieldDef")); QueryLookup queryLookup = queryLookupService.readQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef); List<Object> objects = queryLookupService.executeQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef, queryParams); ModelAndView mav = new ModelAndView("queryLookup"); mav.addObject("objects", objects); PagedListHolder pagedListHolder = new PagedListHolder(objects); pagedListHolder.setMaxLinkedPages(3); pagedListHolder.setPageSize(50); String page = request.getParameter("page"); Integer pg = 0; if (!StringUtils.isBlank(page)) { pg = Integer.valueOf(page); } pagedListHolder.setPage(pg); mav.addObject("pagedListHolder", pagedListHolder); mav.addObject("queryLookup", queryLookup); // mav.addObject("displayColumns", displayColumns); // mav.addObject("parameterMap", request.getParameterMap()); return mav; }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String param = enu.nextElement(); String paramValue = StringUtils.trimToNull(request.getParameter(param)); if (paramValue != null && !param.equalsIgnoreCase("fieldDef") && !param.equalsIgnoreCase("view") && !param.equalsIgnoreCase("resultsOnly")) { queryParams.put(param, paramValue); } } // List<String> displayColumns = new ArrayList<String>(); // displayColumns.add("lastName"); // displayColumns.add("firstName"); String fieldDef = StringUtils.trimToNull(request.getParameter("fieldDef")); QueryLookup queryLookup = queryLookupService.readQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef); List<Object> objects = queryLookupService.executeQueryLookup(SessionServiceImpl.lookupUserSiteName(), fieldDef, queryParams); ModelAndView mav = new ModelAndView("queryLookup"); mav.addObject("objects", objects); PagedListHolder pagedListHolder = new PagedListHolder(objects); pagedListHolder.setMaxLinkedPages(3); pagedListHolder.setPageSize(50); String page = request.getParameter("page"); Integer pg = 0; if (!StringUtils.isBlank(page)) { pg = Integer.valueOf(page); } pagedListHolder.setPage(pg); mav.addObject("pagedListHolder", pagedListHolder); mav.addObject("queryLookup", queryLookup); // mav.addObject("displayColumns", displayColumns); // mav.addObject("parameterMap", request.getParameterMap()); return mav; }
diff --git a/src/r/nodes/truffle/FunctionCall.java b/src/r/nodes/truffle/FunctionCall.java index 4480104..60b0963 100644 --- a/src/r/nodes/truffle/FunctionCall.java +++ b/src/r/nodes/truffle/FunctionCall.java @@ -1,105 +1,106 @@ package r.nodes.truffle; import r.*; import r.data.*; import r.nodes.*; public class FunctionCall extends BaseR { RNode closureExpr; final RSymbol[] names; // arguments of the call (not of the function), in order RNode[] expressions; private static final boolean DEBUG_MATCHING = false; public FunctionCall(ASTNode ast, RNode closureExpr, RSymbol[] argNames, RNode[] argExprs) { super(ast); this.closureExpr = updateParent(closureExpr); this.names = argNames; this.expressions = updateParent(argExprs); } @Override public Object execute(RContext context, RFrame frame) { RClosure tgt = (RClosure) closureExpr.execute(context, frame); RFunction func = tgt.function(); RFrame fframe = new RFrame(tgt.environment(), func); // FIXME: now only eager evaluation (no promises) // FIXME: now no support for "..." RSymbol[] fargs = func.argNames(); RNode[] fdefs = func.argExprs(); Utils.check(fargs.length == fdefs.length); int j; for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance fframe.localExtra(j, -1); } // exact matching on tags (names) j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag != null) { boolean matched = false; for (j = 0; j < fargs.length; j++) { RSymbol ftag = fargs[j]; if (tag == ftag) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i); matched = true; break; } } if (!matched) { // FIXME: fix error reporting - throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + tag.pretty() + ")"); + context.warning(getAST(), "unused argument(s) (" + tag.pretty() + ")"); // FIXME move this string in RError } } } // FIXME: add partial matching on tags // positional matching of remaining arguments j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag == null) { for (;;) { if (j == fargs.length) { // FIXME: fix error reporting throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + expressions[i].getAST() + ")"); } if (fframe.localExtra(j) == -1) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by position at formal index " + i); j++; break; } j++; } } } // providing values for the arguments for (j = 0; j < fargs.length; j++) { int i = (int) fframe.localExtra(j); if (i != -1) { RNode argExp = expressions[i]; if (argExp != null) { fframe.writeAt(j, (RAny) argExp.execute(context, frame)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i); continue; } // note that an argument may be matched, but still have a null expression } RNode defExp = fdefs[j]; if (defExp != null) { fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with default value"); } else { - throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing"); + // throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing"); + // This is not an error ! This error will be reported iff some code try to access it. (Which sucks a bit but is the behaviour) } } RNode code = func.body(); Object res = code.execute(context, fframe); return res; } }
false
true
public Object execute(RContext context, RFrame frame) { RClosure tgt = (RClosure) closureExpr.execute(context, frame); RFunction func = tgt.function(); RFrame fframe = new RFrame(tgt.environment(), func); // FIXME: now only eager evaluation (no promises) // FIXME: now no support for "..." RSymbol[] fargs = func.argNames(); RNode[] fdefs = func.argExprs(); Utils.check(fargs.length == fdefs.length); int j; for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance fframe.localExtra(j, -1); } // exact matching on tags (names) j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag != null) { boolean matched = false; for (j = 0; j < fargs.length; j++) { RSymbol ftag = fargs[j]; if (tag == ftag) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i); matched = true; break; } } if (!matched) { // FIXME: fix error reporting throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + tag.pretty() + ")"); } } } // FIXME: add partial matching on tags // positional matching of remaining arguments j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag == null) { for (;;) { if (j == fargs.length) { // FIXME: fix error reporting throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + expressions[i].getAST() + ")"); } if (fframe.localExtra(j) == -1) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by position at formal index " + i); j++; break; } j++; } } } // providing values for the arguments for (j = 0; j < fargs.length; j++) { int i = (int) fframe.localExtra(j); if (i != -1) { RNode argExp = expressions[i]; if (argExp != null) { fframe.writeAt(j, (RAny) argExp.execute(context, frame)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i); continue; } // note that an argument may be matched, but still have a null expression } RNode defExp = fdefs[j]; if (defExp != null) { fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with default value"); } else { throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing"); } } RNode code = func.body(); Object res = code.execute(context, fframe); return res; }
public Object execute(RContext context, RFrame frame) { RClosure tgt = (RClosure) closureExpr.execute(context, frame); RFunction func = tgt.function(); RFrame fframe = new RFrame(tgt.environment(), func); // FIXME: now only eager evaluation (no promises) // FIXME: now no support for "..." RSymbol[] fargs = func.argNames(); RNode[] fdefs = func.argExprs(); Utils.check(fargs.length == fdefs.length); int j; for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance fframe.localExtra(j, -1); } // exact matching on tags (names) j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag != null) { boolean matched = false; for (j = 0; j < fargs.length; j++) { RSymbol ftag = fargs[j]; if (tag == ftag) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i); matched = true; break; } } if (!matched) { // FIXME: fix error reporting context.warning(getAST(), "unused argument(s) (" + tag.pretty() + ")"); // FIXME move this string in RError } } } // FIXME: add partial matching on tags // positional matching of remaining arguments j = 0; for (int i = 0; i < names.length; i++) { RSymbol tag = names[i]; if (tag == null) { for (;;) { if (j == fargs.length) { // FIXME: fix error reporting throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + expressions[i].getAST() + ")"); } if (fframe.localExtra(j) == -1) { fframe.localExtra(j, i); // remember the index of supplied argument that matches if (DEBUG_MATCHING) Utils.debug("matched formal at index " + j + " by position at formal index " + i); j++; break; } j++; } } } // providing values for the arguments for (j = 0; j < fargs.length; j++) { int i = (int) fframe.localExtra(j); if (i != -1) { RNode argExp = expressions[i]; if (argExp != null) { fframe.writeAt(j, (RAny) argExp.execute(context, frame)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i); continue; } // note that an argument may be matched, but still have a null expression } RNode defExp = fdefs[j]; if (defExp != null) { fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise if (DEBUG_MATCHING) Utils.debug("supplied formal " + fargs[j].pretty() + " with default value"); } else { // throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing"); // This is not an error ! This error will be reported iff some code try to access it. (Which sucks a bit but is the behaviour) } } RNode code = func.body(); Object res = code.execute(context, fframe); return res; }