answer
stringlengths 17
10.2M
|
|---|
package git4idea.branch;
import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.util.Alarm;
import com.intellij.util.EnvironmentUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.Topic;
import com.intellij.util.ui.update.DisposableUpdate;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.Update;
import com.intellij.vcs.log.Hash;
import com.intellij.vcsUtil.VcsFileUtil;
import git4idea.GitLocalBranch;
import git4idea.GitRemoteBranch;
import git4idea.commands.*;
import git4idea.config.GitVcsSettings;
import git4idea.config.GitVersionSpecialty;
import git4idea.i18n.GitBundle;
import git4idea.push.GitPushSupport;
import git4idea.push.GitPushTarget;
import git4idea.repo.*;
import org.jetbrains.annotations.CalledInAny;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.intellij.util.containers.ContainerUtil.*;
import static git4idea.commands.GitAuthenticationMode.NONE;
import static git4idea.commands.GitAuthenticationMode.SILENT;
import static git4idea.config.GitIncomingCheckStrategy.Auto;
import static git4idea.config.GitIncomingCheckStrategy.Never;
import static git4idea.repo.GitRefUtil.addRefsHeadsPrefixIfNeeded;
import static git4idea.repo.GitRefUtil.getResolvedHashes;
import static java.util.stream.Collectors.toSet;
import static one.util.streamex.StreamEx.of;
public class GitBranchIncomingOutgoingManager implements GitRepositoryChangeListener, GitAuthenticationListener, Disposable {
private static final Logger LOG = Logger.getInstance(GitBranchIncomingOutgoingManager.class);
public static final Topic<GitIncomingOutgoingListener> GIT_INCOMING_OUTGOING_CHANGED =
Topic.create("Git incoming outgoing info changed", GitIncomingOutgoingListener.class);
private static final String MAC_DEFAULT_LAUNCH = "com.apple.launchd"; //NON-NLS
private static final boolean HAS_EXTERNAL_SSH_AGENT = hasExternalSSHAgent();
private final @NotNull Object LOCK = new Object();
private final @NotNull Set<GitRepository> myDirtyReposWithIncoming = new HashSet<>();
private final @NotNull Set<GitRepository> myDirtyReposWithOutgoing = new HashSet<>();
private boolean myShouldRequestRemoteInfo;
private final @NotNull MergingUpdateQueue myQueue;
//store map from local branch to related cached remote branch hash per repository
private final @NotNull Map<GitRepository, Set<GitLocalBranch>> myLocalBranchesWithIncoming = new ConcurrentHashMap<>();
private final @NotNull Map<GitRepository, Map<GitLocalBranch, Hash>> myLocalBranchesToFetch = new ConcurrentHashMap<>();
private final @NotNull Map<GitRepository, Set<GitLocalBranch>> myLocalBranchesWithOutgoing = new ConcurrentHashMap<>();
private final @NotNull MultiMap<GitRepository, GitRemote> myErrorMap = MultiMap.createConcurrentSet();
private final @NotNull Project myProject;
private @Nullable ScheduledFuture<?> myPeriodicalUpdater;
private @Nullable MessageBusConnection myConnection;
private final @NotNull MultiMap<GitRepository, GitRemote> myAuthSuccessMap = MultiMap.createConcurrentSet();
private final @NotNull AtomicBoolean myIsUpdating = new AtomicBoolean();
GitBranchIncomingOutgoingManager(@NotNull Project project) {
myProject = project;
myQueue = new MergingUpdateQueue("GitBranchIncomingOutgoingManager", 1000, true, null,
this, null, Alarm.ThreadToUse.POOLED_THREAD);
}
@Override
public void dispose() {
stopScheduling();
}
private static boolean hasExternalSSHAgent() {
String ssh_auth_sock = EnvironmentUtil.getValue("SSH_AUTH_SOCK");
if (ssh_auth_sock == null) return false;
return !StringUtil.contains(ssh_auth_sock, MAC_DEFAULT_LAUNCH);
}
public boolean hasIncomingFor(@Nullable GitRepository repository, @NotNull String localBranchName) {
return shouldCheckIncoming() && getBranchesWithIncoming(repository).contains(new GitLocalBranch(localBranchName));
}
public boolean hasOutgoingFor(@Nullable GitRepository repository, @NotNull String localBranchName) {
return shouldCheckIncomingOutgoing() && getBranchesWithOutgoing(repository).contains(new GitLocalBranch(localBranchName));
}
public boolean shouldCheckIncoming() {
return Registry.is("git.update.incoming.outgoing.info") && GitVcsSettings.getInstance(myProject).getIncomingCheckStrategy() != Never;
}
private static boolean shouldCheckIncomingOutgoing() {
return Registry.is("git.update.incoming.outgoing.info");
}
public static @NotNull GitBranchIncomingOutgoingManager getInstance(@NotNull Project project) {
return ServiceManager.getService(project, GitBranchIncomingOutgoingManager.class);
}
public boolean supportsIncomingOutgoing() {
return GitVersionSpecialty.INCOMING_OUTGOING_BRANCH_INFO.existsIn(myProject);
}
public void activate() {
ApplicationManager.getApplication().invokeLater(() -> {
if (myProject.isDisposed()) return;
if (myConnection == null) {
myConnection = myProject.getMessageBus().connect(this);
myConnection.subscribe(GitRepository.GIT_REPO_CHANGE, this);
myConnection.subscribe(GitAuthenticationListener.GIT_AUTHENTICATION_SUCCESS, this);
}
updateBranchesWithOutgoing();
updateIncomingScheduling();
});
}
public void updateIncomingScheduling() {
if (myPeriodicalUpdater == null && shouldCheckIncoming()) {
updateBranchesWithIncoming(true);
int timeout = Registry.intValue("git.update.incoming.info.time");
myPeriodicalUpdater = JobScheduler.getScheduler().scheduleWithFixedDelay(() -> updateBranchesWithIncoming(true), timeout, timeout,
TimeUnit.MINUTES);
}
else if (myPeriodicalUpdater != null && !shouldCheckIncoming()) {
stopScheduling();
}
}
@CalledInAwt
private void stopScheduling() {
if (myPeriodicalUpdater != null) {
myPeriodicalUpdater.cancel(true);
myPeriodicalUpdater = null;
}
}
@CalledInAny
public void forceUpdateBranches(@Nullable Runnable runAfterUpdate) {
if (!myIsUpdating.compareAndSet(false, true)) return;
updateBranchesWithIncoming(false);
updateBranchesWithOutgoing();
new Task.Backgroundable(myProject, GitBundle.message("branches.update.info.process")) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
Semaphore semaphore = new Semaphore(0);
//to avoid eating events and make semaphore being released we use 'this' here instead of "update"
myQueue.queue(Update.create(this, () -> semaphore.release()));
myQueue.flush();
try {
while (true) {
if (indicator.isCanceled()) break;
if (semaphore.tryAcquire(100, TimeUnit.MILLISECONDS)) break;
}
}
catch (InterruptedException e) {
throw new ProcessCanceledException(e);
}
}
@Override
public void onFinished() {
myIsUpdating.set(false);
if (runAfterUpdate != null) {
runAfterUpdate.run();
}
}
}.queue();
}
public boolean isUpdating() {
return myIsUpdating.get();
}
private void scheduleUpdate() {
myQueue.queue(DisposableUpdate.createDisposable(this, "update", () -> {
List<GitRepository> withIncoming;
List<GitRepository> withOutgoing;
boolean shouldRequestRemoteInfo;
synchronized (LOCK) {
withIncoming = new ArrayList<>(myDirtyReposWithIncoming);
withOutgoing = new ArrayList<>(myDirtyReposWithOutgoing);
shouldRequestRemoteInfo = myShouldRequestRemoteInfo;
myDirtyReposWithIncoming.clear();
myDirtyReposWithOutgoing.clear();
myShouldRequestRemoteInfo = false;
}
for (GitRepository r : withOutgoing) {
myLocalBranchesWithOutgoing.put(r, calculateBranchesWithOutgoing(r));
}
for (GitRepository r : withIncoming) {
if (shouldRequestRemoteInfo) {
myLocalBranchesToFetch.put(r, calculateBranchesToFetch(r));
}
myLocalBranchesWithIncoming.put(r, calcBranchesWithIncoming(r));
}
myProject.getMessageBus().syncPublisher(GIT_INCOMING_OUTGOING_CHANGED).incomingOutgoingInfoChanged();
}));
}
public @NotNull Collection<GitLocalBranch> getBranchesWithIncoming(@Nullable GitRepository repository) {
return getBranches(repository, myLocalBranchesWithIncoming);
}
public @NotNull Collection<GitLocalBranch> getBranchesWithOutgoing(@Nullable GitRepository repository) {
return getBranches(repository, myLocalBranchesWithOutgoing);
}
private void updateBranchesWithIncoming(boolean fromRemote) {
if (!shouldCheckIncoming()) return;
synchronized (LOCK) {
myShouldRequestRemoteInfo = fromRemote;
myDirtyReposWithIncoming.addAll(GitRepositoryManager.getInstance(myProject).getRepositories());
}
scheduleUpdate();
}
private void updateBranchesWithOutgoing() {
if(!shouldCheckIncomingOutgoing()) return;
synchronized (LOCK) {
myDirtyReposWithOutgoing.addAll(GitRepositoryManager.getInstance(myProject).getRepositories());
}
scheduleUpdate();
}
private @NotNull Map<GitLocalBranch, Hash> calculateBranchesToFetch(@NotNull GitRepository repository) {
Map<GitLocalBranch, Hash> result = new HashMap<>();
groupTrackInfoByRemotes(repository).entrySet()
.forEach(entry -> result.putAll(calcBranchesToFetchForRemote(repository, entry.getKey(), entry.getValue(),
getAuthenticationMode(repository, entry.getKey()
))));
return result;
}
private @NotNull Map<GitLocalBranch, Hash> calcBranchesToFetchForRemote(@NotNull GitRepository repository,
@NotNull GitRemote gitRemote,
@NotNull Collection<? extends GitBranchTrackInfo> trackInfoList,
GitAuthenticationMode mode) {
Map<GitLocalBranch, Hash> result = new HashMap<>();
GitBranchesCollection branchesCollection = repository.getBranches();
final Map<String, Hash> remoteNameWithHash =
lsRemote(repository, gitRemote, map(trackInfoList, info -> info.getRemoteBranch().getNameForRemoteOperations()), mode);
for (Map.Entry<String, Hash> hashEntry : remoteNameWithHash.entrySet()) {
String remoteBranchName = hashEntry.getKey();
Hash remoteHash = hashEntry.getValue();
trackInfoList.forEach(info -> {
GitRemoteBranch remoteBranch = info.getRemoteBranch();
Hash localHashForRemoteBranch = branchesCollection.getHash(remoteBranch);
if (localHashForRemoteBranch == null) return;
if (StringUtil.equals(remoteBranchName, addRefsHeadsPrefixIfNeeded(remoteBranch.getNameForRemoteOperations()))) {
if (!localHashForRemoteBranch.equals(remoteHash)) {
result.put(info.getLocalBranch(), localHashForRemoteBranch);
}
}
});
}
return result;
}
private @NotNull Set<GitLocalBranch> calcBranchesWithIncoming(@NotNull GitRepository repository) {
Set<GitLocalBranch> result = new HashSet<>();
GitBranchesCollection branchesCollection = repository.getBranches();
Map<GitLocalBranch, Hash> cachedBranchesToFetch = myLocalBranchesToFetch.get(repository);
branchesCollection.getLocalBranches().forEach(localBranch -> {
GitBranchTrackInfo info = GitBranchUtil.getTrackInfoForBranch(repository, localBranch);
if (info == null) return;
Hash localHashForRemoteBranch = branchesCollection.getHash(info.getRemoteBranch());
Hash localHash = branchesCollection.getHash(localBranch);
if (localHashForRemoteBranch == null) return;
if (hasCommitsForBranch(repository, info.getLocalBranch(), localHash, localHashForRemoteBranch, true)) {
result.add(info.getLocalBranch());
}
else if (cachedBranchesToFetch != null && localHashForRemoteBranch.equals(cachedBranchesToFetch.get(localBranch))) {
result.add(info.getLocalBranch());
}
});
return result;
}
private @NotNull GitAuthenticationMode getAuthenticationMode(@NotNull GitRepository repository,
@NotNull GitRemote remote) {
return (myAuthSuccessMap.get(repository).contains(remote)) ? SILENT : NONE;
}
private boolean shouldAvoidUserInteraction(@NotNull GitRemote remote) {
return GitVcsSettings.getInstance(myProject).getIncomingCheckStrategy() == Auto && HAS_EXTERNAL_SSH_AGENT && containsSSHUrl(remote);
}
private static boolean containsSSHUrl(@NotNull GitRemote remote) {
return exists(remote.getUrls(), url -> !url.startsWith(URLUtil.HTTP_PROTOCOL));
}
private @NotNull Map<String, Hash> lsRemote(@NotNull GitRepository repository,
@NotNull GitRemote remote,
@NotNull List<String> branchRefNames,
@NotNull GitAuthenticationMode authenticationMode) {
Map<String, Hash> result = new HashMap<>();
if (!supportsIncomingOutgoing()) return result;
if (authenticationMode == NONE || (authenticationMode == SILENT && shouldAvoidUserInteraction(remote))) {
myErrorMap.putValue(repository, remote);
return result;
}
VcsFileUtil.chunkArguments(branchRefNames).forEach(refs -> {
List<String> params = newArrayList("--heads", remote.getName()); //NON-NLS
params.addAll(refs);
GitCommandResult lsRemoteResult =
Git.getInstance().runCommand(() -> createLsRemoteHandler(repository, remote, params, authenticationMode));
if (lsRemoteResult.success()) {
Map<String, String> hashWithNameMap = map2MapNotNull(lsRemoteResult.getOutput(), GitRefUtil::parseRefsLine);
result.putAll(getResolvedHashes(hashWithNameMap));
myErrorMap.remove(repository, remote);
myAuthSuccessMap.putValue(repository, remote);
}
else {
myErrorMap.putValue(repository, remote);
}
});
return result;
}
private @NotNull GitLineHandler createLsRemoteHandler(@NotNull GitRepository repository,
@NotNull GitRemote remote,
@NotNull List<String> params, @NotNull GitAuthenticationMode authenticationMode) {
GitLineHandler h = new GitLineHandler(myProject, repository.getRoot(), GitCommand.LS_REMOTE);
h.setIgnoreAuthenticationMode(authenticationMode);
h.addParameters(params);
h.setUrls(remote.getUrls());
return h;
}
private @NotNull Set<GitLocalBranch> calculateBranchesWithOutgoing(@NotNull GitRepository gitRepository) {
Set<GitLocalBranch> branchesWithOutgoing = new HashSet<>();
GitBranchesCollection branchesCollection = gitRepository.getBranches();
for (GitLocalBranch branch : branchesCollection.getLocalBranches()) {
GitPushTarget pushTarget = GitPushSupport.getPushTargetIfExist(gitRepository, branch);
Hash localHashForRemoteBranch = pushTarget != null ? branchesCollection.getHash(pushTarget.getBranch()) : null;
Hash localHash = branchesCollection.getHash(branch);
if (hasCommitsForBranch(gitRepository, branch, localHash, localHashForRemoteBranch, false)) {
branchesWithOutgoing.add(branch);
}
}
return branchesWithOutgoing;
}
private boolean hasCommitsForBranch(@NotNull GitRepository repository,
@NotNull GitLocalBranch localBranch,
@Nullable Hash localBranchHash, @Nullable Hash localHashForRemoteBranch,
boolean incoming) {
if (!supportsIncomingOutgoing()) return false;
if (localHashForRemoteBranch == null || Objects.equals(localBranchHash, localHashForRemoteBranch)) return false;
//run git rev-list --count pushTargetForBranch_or_hash..localName for outgoing ( @{push} can be used only for equal branch names)
//see git-push help -> simple push strategy
//git rev-list --count localName..localName@{u} for incoming
GitLineHandler handler = new GitLineHandler(repository.getProject(), repository.getRoot(), GitCommand.REV_LIST);
handler.setSilent(true);
String branchName = localBranch.getName();
handler.addParameters("--count", incoming
? branchName + ".." + branchName + "@{u}"
: localHashForRemoteBranch.asString() + ".." + branchName);
try {
String output = Git.getInstance().runCommand(handler).getOutputOrThrow().trim();
return !StringUtil.startsWithChar(output, '0');
}
catch (VcsException e) {
LOG.warn("Can't get outgoing info (git rev-list " + branchName + " failed):" + e.getMessage());
return false;
}
}
private static @NotNull Collection<GitLocalBranch> getBranches(@Nullable GitRepository repository,
@NotNull Map<GitRepository, Set<GitLocalBranch>> branchCollection) {
if (repository != null) {
return ObjectUtils.chooseNotNull(branchCollection.get(repository), Collections.emptySet());
}
return of(branchCollection.values()).flatMap(Set::stream).collect(toSet());
}
@Override
public void repositoryChanged(@NotNull GitRepository repository) {
if (!shouldCheckIncomingOutgoing()) return;
synchronized (LOCK) {
myDirtyReposWithOutgoing.add(repository);
myDirtyReposWithIncoming.add(repository);
}
scheduleUpdate();
}
@Override
public void authenticationSucceeded(@NotNull GitRepository repository, @NotNull GitRemote remote) {
if (!shouldCheckIncoming()) return;
myAuthSuccessMap.putValue(repository, remote);
}
private static @NotNull MultiMap<GitRemote, GitBranchTrackInfo> groupTrackInfoByRemotes(@NotNull GitRepository repository) {
return groupBy(repository.getBranchTrackInfos(), GitBranchTrackInfo::getRemote);
}
public interface GitIncomingOutgoingListener {
void incomingOutgoingInfoChanged();
}
}
|
package org.realityforge.arez.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.realityforge.arez.annotations.Container;
/**
* Annotation processor that analyzes Arez annotated source and generates Observable models.
*/
@SuppressWarnings( "Duplicates" )
@AutoService( Processor.class )
@SupportedAnnotationTypes( { "org.realityforge.arez.annotations.Action",
"org.realityforge.arez.annotations.Computed",
"org.realityforge.arez.annotations.Container",
"org.realityforge.arez.annotations.ContainerId",
"org.realityforge.arez.annotations.Observable" } )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public final class ArezProcessor
extends AbstractJavaPoetProcessor
{
private static final ClassName AREZ_CONTEXT_CLASSNAME = ClassName.get( "org.realityforge.arez", "ArezContext" );
private static final ClassName OBSERVABLE_CLASSNAME = ClassName.get( "org.realityforge.arez", "Observable" );
private static final ClassName COMPUTED_VALUE_CLASSNAME = ClassName.get( "org.realityforge.arez", "ComputedValue" );
private static final String FIELD_PREFIX = "$$arez$$_";
private static final String CONTEXT_FIELD_NAME = FIELD_PREFIX + "context";
private static final String NEXT_ID_FIELD_NAME = FIELD_PREFIX + "nextId";
private static final String ID_FIELD_NAME = FIELD_PREFIX + "id";
/**
* {@inheritDoc}
*/
@Override
public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env )
{
final Set<? extends Element> elements = env.getElementsAnnotatedWith( Container.class );
processElements( elements );
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected void process( @Nonnull final Element element )
throws IOException, ArezProcessorException
{
final ContainerDescriptor descriptor = ContainerDescriptorParser.parse( element, processingEnv.getElementUtils() );
emitTypeSpec( descriptor.getPackageElement().getQualifiedName().toString(), builder( descriptor ) );
}
/**
* Build the enhanced class for specified container.
*/
@Nonnull
private TypeSpec builder( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
final TypeElement element = descriptor.getElement();
final AnnotationSpec generatedAnnotation =
AnnotationSpec.builder( Generated.class ).addMember( "value", "$S", getClass().getName() ).build();
final StringBuilder name = new StringBuilder( "Arez_" + element.getSimpleName() );
TypeElement t = element;
while ( NestingKind.TOP_LEVEL != t.getNestingKind() )
{
t = (TypeElement) t.getEnclosingElement();
name.insert( 0, t.getSimpleName() + "$" );
}
final TypeSpec.Builder builder = TypeSpec.classBuilder( name.toString() ).
superclass( TypeName.get( element.asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( descriptor.asDeclaredType() ) ).
addModifiers( Modifier.FINAL ).
addAnnotation( generatedAnnotation );
ProcessorUtil.copyAccessModifiers( element, builder );
buildFields( descriptor, builder );
buildConstructors( descriptor, builder );
if ( !descriptor.isSingleton() )
{
builder.addMethod( buildIdGetter( descriptor ) );
}
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
builder.addMethod( buildObservableGetter( observable ) );
builder.addMethod( buildObservableSetter( observable ) );
}
for ( final ActionDescriptor action : descriptor.getActions() )
{
builder.addMethod( buildAction( descriptor, action ) );
}
for ( final ComputedDescriptor computed : descriptor.getComputeds() )
{
builder.addMethod( buildComputed( computed ) );
}
return builder.build();
}
/**
* Generate the wrapper around Computed method.
*/
@Nonnull
private MethodSpec buildComputed( @Nonnull final ComputedDescriptor descriptor )
throws ArezProcessorException
{
final ExecutableElement computed = descriptor.getComputed();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( computed.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( computed, builder );
ProcessorUtil.copyExceptions( computed, builder );
ProcessorUtil.copyDocumentedAnnotations( computed, builder );
builder.addAnnotation( Override.class );
final TypeMirror returnType = computed.getReturnType();
builder.returns( TypeName.get( returnType ) );
builder.addStatement( "return this.$N.get()", FIELD_PREFIX + descriptor.getName() );
return builder.build();
}
/**
* Generate the action wrapper.
*/
@Nonnull
private MethodSpec buildAction( @Nonnull final ContainerDescriptor containerDescriptor,
@Nonnull final ActionDescriptor descriptor )
throws ArezProcessorException
{
final ExecutableElement action = descriptor.getAction();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( action.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( action, builder );
ProcessorUtil.copyExceptions( action, builder );
ProcessorUtil.copyDocumentedAnnotations( action, builder );
builder.addAnnotation( Override.class );
final TypeMirror returnType = action.getReturnType();
builder.returns( TypeName.get( returnType ) );
final boolean isProcedure = returnType.getKind() == TypeKind.VOID;
final boolean isSafe = action.getThrownTypes().isEmpty();
final StringBuilder statement = new StringBuilder();
final ArrayList<String> parameterNames = new ArrayList<>();
if ( !isProcedure )
{
statement.append( "return " );
}
statement.append( "this.$N." );
parameterNames.add( CONTEXT_FIELD_NAME );
if ( isProcedure && isSafe )
{
statement.append( "safeProcedure" );
}
else if ( isProcedure )
{
statement.append( "procedure" );
}
else if ( isSafe )
{
statement.append( "safeFunction" );
}
else
{
statement.append( "function" );
}
statement.append( "(" );
if ( containerDescriptor.isSingleton() )
{
statement.append( "this.$N.areNamesEnabled() ? $S : null" );
parameterNames.add( CONTEXT_FIELD_NAME );
parameterNames.add( getPrefix( containerDescriptor ) + descriptor.getName() );
}
else
{
statement.append( "this.$N.areNamesEnabled() ? $N() + $S : null" );
parameterNames.add( CONTEXT_FIELD_NAME );
parameterNames.add( ID_FIELD_NAME );
parameterNames.add( descriptor.getName() );
}
statement.append( ", " );
statement.append( descriptor.isMutation() );
statement.append( ", () -> super." );
statement.append( action.getSimpleName() );
statement.append( "(" );
boolean firstParam = true;
for ( final VariableElement element : action.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
statement.append( "," );
}
firstParam = false;
statement.append( "$N" );
}
statement.append( ") )" );
if ( isSafe || action.getThrownTypes().stream().anyMatch( t -> t.toString().equals( "java.lang.Exception" ) ) )
{
builder.addStatement( statement.toString(), parameterNames.toArray() );
}
else
{
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "try" );
codeBlock.addStatement( statement.toString(), parameterNames.toArray() );
for ( final TypeMirror exception : action.getThrownTypes() )
{
codeBlock.nextControlFlow( "catch( final $T e )", exception );
codeBlock.addStatement( "throw e" );
}
codeBlock.nextControlFlow( "catch( final $T e )", RuntimeException.class );
codeBlock.addStatement( "throw e" );
codeBlock.nextControlFlow( "catch( final $T e )", Exception.class );
codeBlock.addStatement( "throw new $T( e )", UndeclaredThrowableException.class );
codeBlock.endControlFlow();
builder.addCode( codeBlock.build() );
}
return builder.build();
}
/**
* Generate the setter that reports that ensures that the access is reported as Observable.
*/
@Nonnull
private MethodSpec buildObservableSetter( @Nonnull final ObservableDescriptor observable )
throws ArezProcessorException
{
final ExecutableElement getter = observable.getGetter();
final ExecutableElement setter = observable.getSetter();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( setter.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( setter, builder );
ProcessorUtil.copyExceptions( getter, builder );
ProcessorUtil.copyDocumentedAnnotations( setter, builder );
builder.addAnnotation( Override.class );
final VariableElement element = setter.getParameters().get( 0 );
final String paramName = element.getSimpleName().toString();
final TypeName type = TypeName.get( element.asType() );
final ParameterSpec.Builder param =
ParameterSpec.builder( type, paramName, Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
final String accessor = "super." + getter.getSimpleName() + "()";
final String mutator = "super." + setter.getSimpleName() + "($N)";
if ( type.isPrimitive() )
{
codeBlock.beginControlFlow( "if ( $N != " + accessor + " )", paramName );
}
else
{
codeBlock.beginControlFlow( "if ( !$T.equals($N, " + accessor + ") )", Objects.class, paramName );
}
codeBlock.addStatement( mutator, paramName );
codeBlock.addStatement( "this.$N.reportChanged()", fieldName( observable ) );
codeBlock.endControlFlow();
builder.addCode( codeBlock.build() );
return builder.build();
}
/**
* Generate the getter for id.
*/
@Nonnull
private MethodSpec buildIdGetter( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
assert !descriptor.isSingleton();
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( ID_FIELD_NAME ).
addModifiers( Modifier.PRIVATE );
builder.returns( TypeName.get( String.class ) );
final ExecutableElement containerId = descriptor.getContainerId();
if ( null == containerId )
{
builder.addStatement( "return $S + $N + $S", getPrefix( descriptor ), ID_FIELD_NAME, "." );
}
else
{
builder.addStatement( "return $S + $N() + $S", getPrefix( descriptor ), containerId.getSimpleName(), "." );
}
return builder.build();
}
/**
* Generate the getter that ensures that the access is reported.
*/
@Nonnull
private MethodSpec buildObservableGetter( @Nonnull final ObservableDescriptor observable )
throws ArezProcessorException
{
final ExecutableElement getter = observable.getGetter();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( getter.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( getter, builder );
ProcessorUtil.copyExceptions( getter, builder );
ProcessorUtil.copyDocumentedAnnotations( getter, builder );
builder.addAnnotation( Override.class );
builder.returns( TypeName.get( getter.getReturnType() ) );
builder.addStatement( "this.$N.reportObserved()", fieldName( observable ) );
builder.addStatement( "return super." + getter.getSimpleName() + "()" );
return builder.build();
}
/**
* Build the fields required to make class Observable. This involves;
* <ul>
* <li>the context field if there is any @Action methods.</li>
* <li>the observable object for every @Observable.</li>
* <li>the ComputedValue object for every @Computed method.</li>
* </ul>
*/
private void buildFields( @Nonnull final ContainerDescriptor descriptor, @Nonnull final TypeSpec.Builder builder )
{
// If we don't have a method for object id but we need one then synthesize it
if ( !descriptor.isSingleton() && null == descriptor.getContainerId() )
{
final FieldSpec.Builder nextIdField =
FieldSpec.builder( TypeName.LONG, NEXT_ID_FIELD_NAME, Modifier.VOLATILE, Modifier.STATIC, Modifier.PRIVATE );
builder.addField( nextIdField.build() );
final FieldSpec.Builder idField =
FieldSpec.builder( TypeName.LONG, ID_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE );
builder.addField( idField.build() );
}
// Create the field that contains the context
{
final FieldSpec.Builder field =
FieldSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
final FieldSpec.Builder field =
FieldSpec.builder( OBSERVABLE_CLASSNAME, fieldName( observable ), Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
for ( final ComputedDescriptor computed : descriptor.getComputeds() )
{
final ParameterizedTypeName typeName =
ParameterizedTypeName.get( COMPUTED_VALUE_CLASSNAME,
TypeName.get( computed.getComputed().getReturnType() ).box() );
final FieldSpec.Builder field =
FieldSpec.builder( typeName,
FIELD_PREFIX + computed.getName(),
Modifier.FINAL,
Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
}
/**
* Return the name of the field for specified Observable.
*/
@Nonnull
private String fieldName( @Nonnull final ObservableDescriptor observable )
{
return FIELD_PREFIX + observable.getName();
}
/**
* Build all constructors as they appear on the Container class.
* Arez Observable fields are populated as required and parameters are passed up to superclass.
*/
private void buildConstructors( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final TypeSpec.Builder builder )
{
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( descriptor.getElement() ) )
{
builder.addMethod( buildConstructor( descriptor, constructor ) );
}
}
/**
* Build a constructor based on the supplied constructor
*/
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final ExecutableElement constructor )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
ProcessorUtil.copyExceptions( constructor, builder );
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
// Add the first context class parameter
{
final ParameterSpec.Builder param =
ParameterSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL ).
addAnnotation( Nonnull.class );
builder.addParameter( param.build() );
}
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
final ExecutableElement containerId = descriptor.getContainerId();
// Synthesize Id if required
if ( !descriptor.isSingleton() && null == containerId )
{
builder.addStatement( "this.$N = $N++", ID_FIELD_NAME, NEXT_ID_FIELD_NAME );
}
builder.addStatement( "this.$N = $N", CONTEXT_FIELD_NAME, CONTEXT_FIELD_NAME );
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
if ( descriptor.isSingleton() )
{
builder.addStatement( "this.$N = this.$N.createObservable( this.$N.areNamesEnabled() ? $S : null )",
fieldName( observable ),
CONTEXT_FIELD_NAME,
CONTEXT_FIELD_NAME,
getPrefix( descriptor ) + observable.getName() );
}
else
{
builder.addStatement( "this.$N = this.$N.createObservable( this.$N.areNamesEnabled() ? $N() + $S : null )",
fieldName( observable ),
CONTEXT_FIELD_NAME,
CONTEXT_FIELD_NAME,
ID_FIELD_NAME,
observable.getName() );
}
}
for ( final ComputedDescriptor computed : descriptor.getComputeds() )
{
if ( descriptor.isSingleton() )
{
//context.createComputedValue( "Person.fullName", super::getFullName, Objects::equals )
builder.addStatement( "this.$N = this.$N.createComputedValue( this.$N.areNamesEnabled() ? $S : null, " +
"super::$N, $T::equals )",
FIELD_PREFIX + computed.getName(),
CONTEXT_FIELD_NAME,
CONTEXT_FIELD_NAME,
getPrefix( descriptor ) + computed.getName(),
computed.getComputed().getSimpleName().toString(),
Objects.class );
}
else
{
builder.addStatement( "this.$N = this.$N.createComputedValue( this.$N.areNamesEnabled() ? $N() + $S : null, " +
"super::$N, $T::equals )",
FIELD_PREFIX + computed.getName(),
CONTEXT_FIELD_NAME,
CONTEXT_FIELD_NAME,
ID_FIELD_NAME,
computed.getName(),
computed.getComputed().getSimpleName().toString(),
Objects.class );
}
}
return builder.build();
}
/**
* Get prefix specified by container if any.
*/
@Nonnull
private String getPrefix( @Nonnull final ContainerDescriptor descriptor )
{
return descriptor.getName().isEmpty() ? "" : descriptor.getName() + ".";
}
}
|
package com.example.component;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
@ArezComponent
public enum EnumModel
{
A, B;
@Observable
public long getField()
{
return 0;
}
@Observable
public void setField( final long field )
{
}
}
|
package org.broadinstitute.sting.gatk.walkers;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.picard.reference.ReferenceSequenceFileFactory;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.util.StringUtil;
import org.broadinstitute.sting.commandline.Argument;
import org.broadinstitute.sting.commandline.Output;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.io.StingSAMFileWriter;
import org.broadinstitute.sting.gatk.refdata.ReadMetaDataTracker;
import org.broadinstitute.sting.utils.BaseUtils;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.clipreads.ClippingOp;
import org.broadinstitute.sting.utils.clipreads.ClippingRepresentation;
import org.broadinstitute.sting.utils.clipreads.ReadClipper;
import org.broadinstitute.sting.utils.collections.Pair;
import org.broadinstitute.sting.utils.sam.ReadUtils;
import java.io.File;
import java.io.PrintStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This ReadWalker provides simple, yet powerful read clipping capabilities. It allows the user to clip bases in reads
* with poor quality scores, that match particular sequences, or that were generated by particular machine cycles.
*/
@Requires({DataSource.READS})
public class ClipReadsWalker extends ReadWalker<ClipReadsWalker.ReadClipperWithData, ClipReadsWalker.ClippingData> {
@Output
PrintStream out;
/**
* an optional argument to dump the reads out to a BAM file
*/
@Argument(fullName = "outputBam", shortName = "ob", doc = "Write output to this BAM filename instead of STDOUT", required = false)
StingSAMFileWriter outputBam = null;
@Argument(fullName = "qTrimmingThreshold", shortName = "QT", doc = "", required = false)
int qTrimmingThreshold = -1;
@Argument(fullName = "cyclesToTrim", shortName = "CT", doc = "String of the form 1-10,20-30 indicating machine cycles to clip from the reads", required = false)
String cyclesToClipArg = null;
@Argument(fullName = "clipSequencesFile", shortName = "XF", doc = "Remove sequences within reads matching these sequences", required = false)
String clipSequenceFile = null;
@Argument(fullName = "clipSequence", shortName = "X", doc = "Remove sequences within reads matching this sequence", required = false)
String[] clipSequencesArgs = null;
@Argument(fullName="read", doc="", required=false)
String onlyDoRead = null;
//@Argument(fullName = "keepCompletelyClipped", shortName = "KCC", doc = "Unfortunately, sometimes a read is completely clipped away but with SOFTCLIP_BASES this results in an invalid CIGAR string. ", required = false)
//boolean keepCompletelyClippedReads = false;
// @Argument(fullName = "onlyClipFirstSeqMatch", shortName = "ESC", doc="Only clip the first occurrence of a clipping sequence, rather than all subsequences within a read that match", required = false)
// boolean onlyClipFirstSeqMatch = false;
@Argument(fullName = "clipRepresentation", shortName = "CR", doc = "How should we actually clip the bases?", required = false)
ClippingRepresentation clippingRepresentation = ClippingRepresentation.WRITE_NS;
/**
* List of sequence that should be clipped from the reads
*/
List<SeqToClip> sequencesToClip = new ArrayList<SeqToClip>();
/**
* List of cycle start / stop pairs (0-based, stop is included in the cycle to remove) to clip from the reads
*/
List<Pair<Integer, Integer>> cyclesToClip = null;
public class ReadClipperWithData extends ReadClipper {
private ClippingData data;
public ReadClipperWithData(SAMRecord read) {
super(read);
}
public ClippingData getData() {
return data;
}
public void setData(ClippingData data) {
this.data = data;
}
}
/**
* The initialize function.
*/
public void initialize() {
if (qTrimmingThreshold >= 0) {
logger.info(String.format("Creating Q-score clipper with threshold %d", qTrimmingThreshold));
}
// Initialize the sequences to clip
if (clipSequencesArgs != null) {
int i = 0;
for (String toClip : clipSequencesArgs) {
i++;
ReferenceSequence rs = new ReferenceSequence("CMDLINE-" + i, -1, StringUtil.stringToBytes(toClip));
addSeqToClip(rs.getName(), rs.getBases());
}
}
if (clipSequenceFile != null) {
ReferenceSequenceFile rsf = ReferenceSequenceFileFactory.getReferenceSequenceFile(new File(clipSequenceFile));
while (true) {
ReferenceSequence rs = rsf.nextSequence();
if (rs == null)
break;
else {
addSeqToClip(rs.getName(), rs.getBases());
}
}
}
// Initialize the cycle ranges to clip
if (cyclesToClipArg != null) {
cyclesToClip = new ArrayList<Pair<Integer, Integer>>();
for (String range : cyclesToClipArg.split(",")) {
try {
String[] elts = range.split("-");
int start = Integer.parseInt(elts[0]) - 1;
int stop = Integer.parseInt(elts[1]) - 1;
if (start < 0) throw new Exception();
if (stop < start) throw new Exception();
logger.info(String.format("Creating cycle clipper %d-%d", start, stop));
cyclesToClip.add(new Pair<Integer, Integer>(start, stop));
} catch (Exception e) {
throw new RuntimeException("Badly formatted cyclesToClip argument: " + cyclesToClipArg);
}
}
}
if (outputBam != null) {
EnumSet<ClippingRepresentation> presorted = EnumSet.of(ClippingRepresentation.WRITE_NS, ClippingRepresentation.WRITE_NS_Q0S, ClippingRepresentation.WRITE_Q0S);
outputBam.setPresorted(presorted.contains(clippingRepresentation));
}
}
/**
* Helper function that adds a seq with name and bases (as bytes) to the list of sequences to be clipped
*
* @param name
* @param bases
*/
private void addSeqToClip(String name, byte[] bases) {
SeqToClip clip = new SeqToClip(name, StringUtil.bytesToString(bases));
sequencesToClip.add(clip);
logger.info(String.format("Creating sequence clipper %s: %s/%s", clip.name, clip.seq, clip.revSeq));
}
/**
* The reads map function.
*
* @param ref the reference bases that correspond to our read, if a reference was provided
* @param read the read itself, as a SAMRecord
* @return the ReadClipper object describing what should be done to clip this read
*/
public ReadClipperWithData map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
if ( onlyDoRead == null || read.getReadName().equals(onlyDoRead) ) {
if ( clippingRepresentation == ClippingRepresentation.HARDCLIP_BASES ) {
read = ReadUtils.replaceSoftClipsWithMatches(read);
}
ReadClipperWithData clipper = new ReadClipperWithData(read);
// run all three clipping modules
clipBadQualityScores(clipper);
clipCycles(clipper);
clipSequences(clipper);
return clipper;
}
return null;
}
/**
* clip sequences from the reads that match all of the sequences in the global sequencesToClip variable.
* Adds ClippingOps for each clip to clipper.
*
* @param clipper
*/
private void clipSequences(ReadClipperWithData clipper) {
if (sequencesToClip != null) { // don't bother if we don't have any sequences to clip
SAMRecord read = clipper.getRead();
for (SeqToClip stc : sequencesToClip) {
// we have a pattern for both the forward and the reverse strands
Pattern pattern = read.getReadNegativeStrandFlag() ? stc.revPat : stc.fwdPat;
String bases = read.getReadString();
Matcher match = pattern.matcher(bases);
// keep clipping until match.find() says it can't find anything else
boolean found = true; // go through at least once
while (found) {
found = match.find();
//System.out.printf("Matching %s against %s/%s => %b%n", bases, stc.seq, stc.revSeq, found);
if (found) {
int start = match.start();
int stop = match.end() - 1;
//ClippingOp op = new ClippingOp(ClippingOp.ClippingType.MATCHES_CLIP_SEQ, start, stop, stc.seq);
ClippingOp op = new ClippingOp(start, stop);
clipper.addOp(op);
ClippingData data = new ClippingData(sequencesToClip);
data.incSeqClippedBases(stc.seq, op.getLength());
clipper.setData(data);
}
}
}
}
}
/**
* Convenence function that takes a read and the start / stop clipping positions based on the forward
* strand, and returns start/stop values appropriate for the strand of the read.
*
* @param read
* @param start
* @param stop
* @return
*/
private Pair<Integer, Integer> strandAwarePositions(SAMRecord read, int start, int stop) {
if (read.getReadNegativeStrandFlag())
return new Pair<Integer, Integer>(read.getReadLength() - stop - 1, read.getReadLength() - start - 1);
else
return new Pair<Integer, Integer>(start, stop);
}
/**
* clip bases at cycles between the ranges in cyclesToClip by adding appropriate ClippingOps to clipper.
*
* @param clipper
*/
private void clipCycles(ReadClipperWithData clipper) {
if (cyclesToClip != null) {
SAMRecord read = clipper.getRead();
for (Pair<Integer, Integer> p : cyclesToClip) { // iterate over each cycle range
int cycleStart = p.first;
int cycleStop = p.second;
if (cycleStart < read.getReadLength()) {
// only try to clip if the cycleStart is less than the read's length
if (cycleStop >= read.getReadLength())
// we do tolerate [for convenience) clipping when the stop is beyond the end of the read
cycleStop = read.getReadLength() - 1;
Pair<Integer, Integer> startStop = strandAwarePositions(read, cycleStart, cycleStop);
int start = startStop.first;
int stop = startStop.second;
//ClippingOp op = new ClippingOp(ClippingOp.ClippingType.WITHIN_CLIP_RANGE, start, stop, null);
ClippingOp op = new ClippingOp(start, stop);
clipper.addOp(op);
ClippingData data = new ClippingData(sequencesToClip);
data.incNRangeClippedBases(op.getLength());
clipper.setData(data);
}
}
}
}
/**
* Clip bases from the read in clipper from
* <p/>
* argmax_x{ \sum{i = x + 1}^l (qTrimmingThreshold - qual)
* <p/>
* to the end of the read. This is blatantly stolen from BWA.
* <p/>
* Walk through the read from the end (in machine cycle order) to the beginning, calculating the
* running sum of qTrimmingThreshold - qual. While we do this, we track the maximum value of this
* sum where the delta > 0. After the loop, clipPoint is either -1 (don't do anything) or the
* clipping index in the read (from the end).
*
* @param clipper
*/
private void clipBadQualityScores(ReadClipperWithData clipper) {
SAMRecord read = clipper.getRead();
int readLen = read.getReadBases().length;
byte[] quals = read.getBaseQualities();
int clipSum = 0, lastMax = -1, clipPoint = -1; // -1 means no clip
for (int i = readLen - 1; i >= 0; i
int baseIndex = read.getReadNegativeStrandFlag() ? readLen - i - 1 : i;
byte qual = quals[baseIndex];
clipSum += (qTrimmingThreshold - qual);
if (clipSum >= 0 && (clipSum >= lastMax)) {
lastMax = clipSum;
clipPoint = baseIndex;
}
}
if (clipPoint != -1) {
int start = read.getReadNegativeStrandFlag() ? 0 : clipPoint;
int stop = read.getReadNegativeStrandFlag() ? clipPoint : readLen - 1;
//clipper.addOp(new ClippingOp(ClippingOp.ClippingType.LOW_Q_SCORES, start, stop, null));
ClippingOp op = new ClippingOp(start, stop);
clipper.addOp(op);
ClippingData data = new ClippingData(sequencesToClip);
data.incNQClippedBases(op.getLength());
clipper.setData(data);
}
}
/**
* reduceInit is called once before any calls to the map function. We use it here to setup the output
* bam file, if it was specified on the command line
*
* @return
*/
public ClippingData reduceInit() {
return new ClippingData(sequencesToClip);
}
public ClippingData reduce(ReadClipperWithData clipper, ClippingData data) {
if ( clipper == null )
return data;
SAMRecord clippedRead = clipper.clipRead(clippingRepresentation);
if (outputBam != null) {
outputBam.addAlignment(clippedRead);
} else {
out.println(clippedRead.format());
}
data.nTotalReads++;
data.nTotalBases += clipper.getRead().getReadLength();
if (clipper.wasClipped()) {
data.nClippedReads++;
}
data.addData(clipper.getData());
return data;
}
public void onTraversalDone(ClippingData data) {
out.printf(data.toString());
}
// utility classes
private static class SeqToClip {
String name;
String seq, revSeq;
Pattern fwdPat, revPat;
public SeqToClip(String name, String seq) {
this.name = name;
this.seq = seq;
this.fwdPat = Pattern.compile(seq, Pattern.CASE_INSENSITIVE);
this.revSeq = BaseUtils.simpleReverseComplement(seq);
this.revPat = Pattern.compile(revSeq, Pattern.CASE_INSENSITIVE);
}
}
public static class ClippingData {
public long nTotalReads = 0;
public long nTotalBases = 0;
public long nClippedReads = 0;
public long nClippedBases = 0;
public long nQClippedBases = 0;
public long nRangeClippedBases = 0;
public long nSeqClippedBases = 0;
HashMap<String, Long> seqClipCounts = new HashMap<String, Long>();
public ClippingData(List<SeqToClip> clipSeqs) {
for (SeqToClip clipSeq : clipSeqs) {
seqClipCounts.put(clipSeq.seq, 0L);
}
}
public void incNQClippedBases(int n) {
nQClippedBases += n;
nClippedBases += n;
}
public void incNRangeClippedBases(int n) {
nRangeClippedBases += n;
nClippedBases += n;
}
public void incSeqClippedBases(final String seq, int n) {
nSeqClippedBases += n;
nClippedBases += n;
seqClipCounts.put(seq, seqClipCounts.get(seq) + n);
}
public void addData (ClippingData data) {
nTotalReads += data.nTotalReads;
nTotalBases += data.nTotalBases;
nClippedReads += data.nClippedReads;
nClippedBases += data.nClippedBases;
nQClippedBases += data.nQClippedBases;
nRangeClippedBases += data.nRangeClippedBases;
nSeqClippedBases += data.nSeqClippedBases;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(Utils.dupString('-', 80) + "\n");
s.append(String.format("Number of examined reads %d%n", nTotalReads));
s.append(String.format("Number of clipped reads %d%n", nClippedReads));
s.append(String.format("Percent of clipped reads %.2f%n", (100.0 * nClippedReads) / nTotalReads));
s.append(String.format("Number of examined bases %d%n", nTotalBases));
s.append(String.format("Number of clipped bases %d%n", nClippedBases));
s.append(String.format("Percent of clipped bases %.2f%n", (100.0 * nClippedBases) / nTotalBases));
s.append(String.format("Number of quality-score clipped bases %d%n", nQClippedBases));
s.append(String.format("Number of range clipped bases %d%n", nRangeClippedBases));
s.append(String.format("Number of sequence clipped bases %d%n", nSeqClippedBases));
for (Map.Entry<String, Long> elt : seqClipCounts.entrySet()) {
s.append(String.format(" %8d clip sites matching %s%n", elt.getValue(), elt.getKey()));
}
s.append(Utils.dupString('-', 80) + "\n");
return s.toString();
}
}
}
|
package org.jboss.jbossts.qa.junit.testgroup;
import org.jboss.jbossts.qa.junit.Task;
import org.jboss.jbossts.qa.junit.TestGroupBase;
import org.junit.Test;
/**
* QA tests for JTS module.
*/
public class TestGroup_jtsremote extends TestGroupBase
{
public TestGroup_jtsremote() {
isRecoveryManagerNeeded = true;
}
@Test public void JTSRemote_DistributedHammerTest1() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
Task server2 = createTask("server2", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server2.start("$(2)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.hammer.DistributedHammer1.class, "$(1)", "$(2)");
server1.terminate();
server2.terminate();
}
// TODO re-enable when CI job narayana-JBTM-1211 is fixed
public void JTSRemote_DistributedHammerTest2() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
Task server2 = createTask("server2", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server2.start("$(2)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.hammer.DistributedHammer2.class, "$(1)", "$(2)");
server1.terminate();
server2.terminate();
}
@Test public void JTSRemote_DistributedHammerTest3() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
Task server2 = createTask("server2", com.hp.mwtests.ts.jts.remote.servers.HammerServer.class, Task.TaskType.EXPECT_READY, 480);
server2.start("$(2)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.hammer.DistributedHammer3.class, "$(1)", "$(2)");
server1.terminate();
server2.terminate();
}
@Test public void JTSRemote_ExplicitPropagationTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.ExplicitStackServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.arjuna.ExplicitArjunaClient.class, "$(1)");
server1.terminate();
}
@Test public void JTSRemote_ImplicitPropagationTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.StackServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.arjuna.ImplicitArjunaClient.class, "$(1)");
server1.terminate();
}
@Test public void JTSRemote_ImplicitGridTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.ImplGridServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.implicit.ImplicitClient.class, "$(1)");
server1.terminate();
}
@Test public void JTSRemote_CurrentTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.GridServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.current.CurrentTest.class, "$(1)");
server1.terminate();
}
@Test public void JTSRemote_ExplicitInterpositionTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.SetGetServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.explicitinterposition.ExplicitInterClient.class, "$(1)");
server1.terminate();
}
@Test public void JTSRemote_TimeoutTest() {
Task server1 = createTask("server1", com.hp.mwtests.ts.jts.remote.servers.SetGetServer.class, Task.TaskType.EXPECT_READY, 480);
server1.start("$(1)");
startAndWaitForClient(com.hp.mwtests.ts.jts.remote.timeout.TimeoutClient.class, "$(1)");
server1.terminate();
}
}
|
package mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XEnumerationAccess;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XNamedRanges;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.table.CellAddress;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
public class ScIndexEnumeration_NamedRangesEnumeration extends TestCase {
static XSpreadsheetDocument xSheetDoc = null;
/**
* Creates Spreadsheet document.
*/
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() );
try {
log.println( "creating a Spreadsheet document" );
xSheetDoc = SOF.createCalcDoc(null);
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
/**
* Disposes Spreadsheet document.
*/
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
XComponent oComp = (XComponent)
UnoRuntime.queryInterface (XComponent.class, xSheetDoc) ;
util.DesktopTools.closeDoc(oComp);
}
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) {
XInterface oObj = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "Creating a test environment" );
log.println("Getting test object ");
// Getting named ranges.
XPropertySet docProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, xSheetDoc);
Object ranges = null;
try {
ranges = docProps.getPropertyValue("NamedRanges");
} catch(com.sun.star.lang.WrappedTargetException e){
e.printStackTrace(log);
throw new StatusException("Couldn't get NamedRanges", e);
} catch(com.sun.star.beans.UnknownPropertyException e){
e.printStackTrace(log);
throw new StatusException("Couldn't get NamedRanges", e);
}
XNamedRanges xNamedRanges = (XNamedRanges)
UnoRuntime.queryInterface(XNamedRanges.class, ranges);
CellRangeAddress DataArea = new CellRangeAddress((short)0, 0, 0, 2, 2);
CellAddress base = new CellAddress(DataArea.Sheet,
DataArea.StartColumn,
DataArea.StartRow);
xNamedRanges.addNewByName("ANamedRange", "A1:B2", base, 0);
CellAddress listOutputPosition = new CellAddress((short)0, 1, 1);
xNamedRanges.outputList(listOutputPosition);
oObj = xNamedRanges;
XEnumerationAccess ea = (XEnumerationAccess)
UnoRuntime.queryInterface(XEnumerationAccess.class,oObj);
oObj = ea.createEnumeration();
log.println("ImplementationName: "+util.utils.getImplName(oObj));
// creating test environment
TestEnvironment tEnv = new TestEnvironment( oObj );
tEnv.addObjRelation("ENUM",ea);
return tEnv;
}
}
|
package org.innovateuk.ifs.registration.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.registration.form.InternalUserRegistrationForm;
import org.innovateuk.ifs.registration.populator.InternalUserRegistrationModelPopulator;
import org.innovateuk.ifs.registration.service.InternalUserService;
import org.innovateuk.ifs.registration.viewmodel.InternalUserRegistrationViewModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.class)
public class InternalUserRegistrationControllerTest extends BaseControllerMockMVCTest<InternalUserRegistrationController> {
private static final String URL_PREFIX = "/registration";
@Mock
private InternalUserRegistrationModelPopulator internalUserRegistrationModelPopulatorMock;
@Mock
private InternalUserService internalUserServiceMock;
@Override
protected InternalUserRegistrationController supplyControllerUnderTest() {
return new InternalUserRegistrationController();
}
@Test
public void testYourDetails() throws Exception {
setLoggedInUser(null);
when(internalUserRegistrationModelPopulatorMock.populateModel("hash")).thenReturn(new InternalUserRegistrationViewModel("Arden Pimenta", "Project Finance", "arden.pimenta@innovateuk.test"));
mockMvc.perform(get(URL_PREFIX + "/hash/register"))
.andExpect(status().isOk())
.andExpect(view().name("registration/register"));
}
@Test
public void testSubmitYourDetails() throws Exception {
setLoggedInUser(null);
InternalUserRegistrationForm registrationForm = new InternalUserRegistrationForm("Arden", "Pimenta", "Passw0rd");
when(internalUserServiceMock.createInternalUser("hash", registrationForm)).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/hash/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("firstName", registrationForm.getFirstName())
.param("lastName", registrationForm.getLastName())
.param("password", registrationForm.getPassword()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/registration/hash/register/account-created"));
}
@Test
public void testAccountCreated() throws Exception {
setLoggedInUser(null);
when(inviteUserRestServiceMock.checkExistingUser("hash")).thenReturn(RestResult.restSuccess(true));
mockMvc.perform(get(URL_PREFIX + "/hash/register/account-created"))
.andExpect(status().isOk())
.andExpect(view().name("registration/account-created"));
}
}
|
package com.opengamma.analytics.financial.interestrate.future.method;
import com.opengamma.analytics.financial.interestrate.InterestRateCurveSensitivity;
import com.opengamma.analytics.financial.interestrate.PresentValueCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.future.derivative.BondFutureOptionPremiumTransaction;
import com.opengamma.analytics.financial.model.option.definition.YieldCurveWithBlackCubeBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.CurrencyAmount;
public final class BondFutureOptionPremiumTransactionBlackSurfaceMethod {
private static final BondFutureOptionPremiumTransactionBlackSurfaceMethod INSTANCE = new BondFutureOptionPremiumTransactionBlackSurfaceMethod();
private static final BondFutureOptionPremiumSecurityBlackSurfaceMethod METHOD = BondFutureOptionPremiumSecurityBlackSurfaceMethod.getInstance();
public static BondFutureOptionPremiumTransactionBlackSurfaceMethod getInstance() {
return INSTANCE;
}
private BondFutureOptionPremiumTransactionBlackSurfaceMethod() {
}
/**
* Compute the present value of a future transaction from a quoted price.
* @param option The future option, not null
* @param curves The curves, not null
* @param price The quoted price
* @return The present value.
*/
public CurrencyAmount presentValueFromPrice(final BondFutureOptionPremiumTransaction option, final YieldCurveBundle curves, final double price) {
ArgumentChecker.notNull(option, "option");
ArgumentChecker.notNull(curves, "curves");
final PresentValueCalculator pvc = PresentValueCalculator.getInstance();
final double premiumPV = pvc.visit(option.getPremium(), curves);
final double optionPV = price * option.getQuantity() * option.getUnderlyingOption().getUnderlyingFuture().getNotional();
return CurrencyAmount.of(option.getUnderlyingOption().getCurrency(), optionPV + premiumPV);
}
/**
* Computes the present value curve sensitivity of a transaction.
* @param transaction The future option transaction.
* @param curves The yield curve bundle.
* @return The present value curve sensitivity.
*/
public InterestRateCurveSensitivity presentValueCurveSensitivity(final BondFutureOptionPremiumTransaction transaction, final YieldCurveBundle curves) {
ArgumentChecker.notNull(transaction, "transaction");
ArgumentChecker.notNull(curves, "curves");
final InterestRateCurveSensitivity securitySensitivity = METHOD.priceCurveSensitivity(transaction.getUnderlyingOption(), curves);
return securitySensitivity.multiply(transaction.getQuantity() * transaction.getUnderlyingOption().getUnderlyingFuture().getNotional());
}
public CurrencyAmount presentValue(final BondFutureOptionPremiumTransaction transaction, final YieldCurveBundle curves) {
ArgumentChecker.notNull(transaction, "transaction");
ArgumentChecker.notNull(curves, "curves");
final double priceSecurity = METHOD.optionPrice(transaction.getUnderlyingOption(), curves);
final CurrencyAmount pvTransaction = presentValueFromPrice(transaction, curves, priceSecurity);
return pvTransaction;
}
/**
* Computes the present value gamma of a transaction.
* This is with respect to futures rate
* @param transaction The future option transaction.
* @param blackData The curve and Black volatility data.
* @return The gamma.
*/
public double presentValueGamma(final BondFutureOptionPremiumTransaction transaction, final YieldCurveWithBlackCubeBundle blackData) {
ArgumentChecker.notNull(transaction, "transaction");
ArgumentChecker.notNull(blackData, "Black data");
final double securityGamma = METHOD.optionPriceGamma(transaction.getUnderlyingOption(), blackData);
final double txnGamma = securityGamma * transaction.getQuantity() * transaction.getUnderlyingOption().getUnderlyingFuture().getNotional();
return txnGamma;
}
/**
* Computes the present value delta of a transaction.
* This is with respect to futures rate
* @param transaction The future option transaction.
* @param blackData The curve and Black volatility data.
* @return The delta.
*/
public double presentValueDelta(final BondFutureOptionPremiumTransaction transaction, final YieldCurveWithBlackCubeBundle blackData) {
ArgumentChecker.notNull(transaction, "transaction");
ArgumentChecker.notNull(blackData, "Black data");
final double securityDelta = METHOD.optionPriceDelta(transaction.getUnderlyingOption(), blackData);
final double txnDelta = securityDelta * transaction.getQuantity() * transaction.getUnderlyingOption().getUnderlyingFuture().getNotional();
return txnDelta;
}
}
|
package foam.nanos.cron;
import bsh.EvalError;
import bsh.Interpreter;
import foam.core.ContextAwareSupport;
import foam.core.Detachable;
import foam.core.FObject;
import foam.dao.*;
import foam.mlang.MLang;
import foam.mlang.sink.Min;
import foam.nanos.NanoService;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Date;
public class CronScheduler
extends ContextAwareSupport
implements NanoService
{
protected MapDAO cronDAO_;
/**
* Gets the minimum scheduled cron job
*
* @return Date of the minimum scheduled cron job
*/
private Date getMinScheduledTime() {
Min min = (Min) MLang.MIN(Cron.SCHEDULED_TIME);
cronDAO_.select(min);
return ((Cron) min.getValue()).getScheduledTime();
}
/**
* Runs a Cron job script
*
* @param cron the cron job to run
* @return the updated cron job
*/
private void runCronJob(Cron cron) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Interpreter shell = new Interpreter();
try {
shell.set("currentCron", cron);
cron.setOutput("");
shell.setOut(ps);
shell.eval(cron.getCode());
} catch (EvalError e) {
e.printStackTrace();
}
cron.setLastRun(new Date());
ps.flush();
cron.setOutput(baos.toString());
// set to next scheduled time
cron.setScheduledTime(cron.getNextScheduledTime());
}
private final Thread cronJobs = new Thread() {
@Override
public void run() {
try {
while (true) {
Date dtnow = new Date();
((AbstractDAO) cronDAO_.where(MLang.LTE(Cron.SCHEDULED_TIME, dtnow))).select(new AbstractSink() {
@Override
public void put(FObject obj, Detachable sub) {
runCronJob((Cron) obj);
cronDAO_.put(obj);
}
});
Date minScheduledTime = getMinScheduledTime();
Thread.sleep(minScheduledTime.getTime() - dtnow.getTime());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public void start() {
cronDAO_ = (MapDAO) getX().get("MapDAO");
cronJobs.start();
}
}
|
package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class MainPanel extends JPanel {
public MainPanel() {
super(new BorderLayout());
Object[] columnNames = {Status.INDETERMINATE, "Integer", "String"};
Object[][] data = {{true, 1, "BBB"}, {false, 12, "AAA"},
{true, 2, "DDD"}, {false, 5, "CCC"},
{true, 3, "EEE"}, {false, 6, "GGG"},
{true, 4, "FFF"}, {false, 7, "HHH"}};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model) {
@Override public void updateUI() {
super.updateUI();
//XXX: Nimbus
TableCellRenderer r = getDefaultRenderer(Boolean.class);
if(r instanceof JComponent) {
((JComponent)r).updateUI();
}
}
@Override public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
if(c instanceof JCheckBox) {
JCheckBox b = (JCheckBox)c;
b.setBackground(getSelectionBackground());
b.setBorderPainted(true);
}
return c;
}
};
int modelColmunIndex = 0;
TableCellRenderer renderer = new HeaderRenderer(table.getTableHeader(), modelColmunIndex);
// for(int i=0;i<table.getColumnCount();i++) {
// table.getColumnModel().getColumn(i).setHeaderRenderer(renderer);
// table.getColumnModel().getColumn(modelColmunIndex).setHeaderValue(Status.INDETERMINATE);
table.getColumnModel().getColumn(modelColmunIndex).setHeaderRenderer(renderer);
model.addTableModelListener(new HeaderCheckBoxHandler(table, modelColmunIndex));
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
private JComponent makeTitledPanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.add(c);
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class HeaderRenderer extends JCheckBox implements TableCellRenderer {
private final JLabel label = new JLabel("Check All");
private int targetColumnIndex;
public HeaderRenderer(JTableHeader header, int index) {
super((String)null);
this.targetColumnIndex = index;
setOpaque(false);
setFont(header.getFont());
header.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
JTableHeader header = (JTableHeader)e.getSource();
JTable table = header.getTable();
TableColumnModel columnModel = table.getColumnModel();
int vci = columnModel.getColumnIndexAtX(e.getX());
int mci = table.convertColumnIndexToModel(vci);
if(mci == targetColumnIndex) {
TableColumn column = columnModel.getColumn(vci);
Object v = column.getHeaderValue();
boolean b = Status.DESELECTED.equals(v)?true:false;
TableModel m = table.getModel();
for(int i=0; i<m.getRowCount(); i++) m.setValueAt(b, i, mci);
column.setHeaderValue(b?Status.SELECTED:Status.DESELECTED);
//header.repaint();
}
}
});
}
@Override public Component getTableCellRendererComponent(JTable tbl, Object val, boolean isS, boolean hasF, int row, int col) {
TableCellRenderer r = tbl.getTableHeader().getDefaultRenderer();
JLabel l =(JLabel)r.getTableCellRendererComponent(tbl, val, isS, hasF, row, col);
if(targetColumnIndex==tbl.convertColumnIndexToModel(col)) {
if(val instanceof Status) {
switch((Status)val) {
case SELECTED: setSelected(true); setEnabled(true); break;
case DESELECTED: setSelected(false); setEnabled(true); break;
case INDETERMINATE: setSelected(true); setEnabled(false); break;
}
}else{
setSelected(true); setEnabled(false);
}
label.setIcon(new ComponentIcon(this));
l.setIcon(new ComponentIcon(label));
l.setText(null); //XXX: Nimbus???
// l.setHorizontalAlignment(SwingConstants.CENTER);
//}else{
// l.setHorizontalAlignment(SwingConstants.LEFT);
}
// System.out.println("getHeaderRect: " + tbl.getTableHeader().getHeaderRect(col));
// System.out.println("getPreferredSize: " + l.getPreferredSize());
// System.out.println("getMaximunSize: " + l.getMaximumSize());
// if(l.getPreferredSize().height>1000) { //XXX: Nimbus???
// System.out.println(l.getPreferredSize().height);
// Rectangle rect = tbl.getTableHeader().getHeaderRect(col);
// l.setPreferredSize(new Dimension(0, rect.height));
return l;
}
// @Override public void updateUI() {
// setText(null); //XXX: Nimbus???
// super.updateUI();
}
class HeaderCheckBoxHandler implements TableModelListener{
private final JTable table;
private final int targetColumnIndex;
public HeaderCheckBoxHandler(JTable table, int index) {
this.table = table;
this.targetColumnIndex = index;
}
@Override public void tableChanged(TableModelEvent e) {
if(e.getType()==TableModelEvent.UPDATE && e.getColumn()==targetColumnIndex) {
int vci = table.convertColumnIndexToView(targetColumnIndex);
TableColumn column = table.getColumnModel().getColumn(vci);
if(!Status.INDETERMINATE.equals(column.getHeaderValue())) {
column.setHeaderValue(Status.INDETERMINATE);
}else{
boolean selected = true, deselected = true;
TableModel m = table.getModel();
for(int i=0; i<m.getRowCount(); i++) {
Boolean b = (Boolean)m.getValueAt(i, targetColumnIndex);
selected &= b; deselected &= !b;
}
if(selected) {
column.setHeaderValue(Status.SELECTED);
}else if(deselected) {
column.setHeaderValue(Status.DESELECTED);
}else{
return;
}
}
JTableHeader h = table.getTableHeader();
h.repaint(h.getHeaderRect(vci));
}
}
}
class ComponentIcon implements Icon{
private final JComponent cmp;
public ComponentIcon(JComponent cmp) {
this.cmp = cmp;
}
@Override public int getIconWidth() {
return cmp.getPreferredSize().width;
}
@Override public int getIconHeight() {
return cmp.getPreferredSize().height;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
SwingUtilities.paintComponent(g, cmp, (Container)c, x, y, getIconWidth(), getIconHeight());
}
}
enum Status { SELECTED, DESELECTED, INDETERMINATE }
|
package org.elasticsearch.index.mapper;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.exc.InputCoercionException;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.HalfFloatPoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.IndexSortSortedNumericDocValuesRangeQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParser.Token;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexNumericFieldData.NumericType;
import org.elasticsearch.index.fielddata.plain.SortedNumericIndexFieldData;
import org.elasticsearch.index.query.SearchExecutionContext;
import org.elasticsearch.script.DoubleFieldScript;
import org.elasticsearch.script.LongFieldScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptCompiler;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.lookup.FieldValues;
import org.elasticsearch.search.lookup.SearchLookup;
import java.io.IOException;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/** A {@link FieldMapper} for numeric types: byte, short, int, long, float and double. */
public class NumberFieldMapper extends FieldMapper {
public static final Setting<Boolean> COERCE_SETTING =
Setting.boolSetting("index.mapping.coerce", true, Property.IndexScope);
private static NumberFieldMapper toType(FieldMapper in) {
return (NumberFieldMapper) in;
}
public static class Builder extends FieldMapper.Builder {
private final Parameter<Boolean> indexed = Parameter.indexParam(m -> toType(m).indexed, true);
private final Parameter<Boolean> hasDocValues = Parameter.docValuesParam(m -> toType(m).hasDocValues, true);
private final Parameter<Boolean> stored = Parameter.storeParam(m -> toType(m).stored, false);
private final Parameter<Explicit<Boolean>> ignoreMalformed;
private final Parameter<Explicit<Boolean>> coerce;
private final Parameter<Number> nullValue;
private final Parameter<Script> script = Parameter.scriptParam(m -> toType(m).script);
private final Parameter<String> onScriptError = Parameter.onScriptErrorParam(m -> toType(m).onScriptError, script);
private final Parameter<Boolean> dimension;
private final Parameter<Map<String, String>> meta = Parameter.metaParam();
private final ScriptCompiler scriptCompiler;
private final NumberType type;
public Builder(String name, NumberType type, ScriptCompiler compiler, Settings settings) {
this(name, type, compiler, IGNORE_MALFORMED_SETTING.get(settings), COERCE_SETTING.get(settings));
}
public static Builder docValuesOnly(String name, NumberType type) {
Builder builder = new Builder(name, type, ScriptCompiler.NONE, false, false);
builder.indexed.setValue(false);
builder.dimension.setValue(false);
return builder;
}
public Builder(String name, NumberType type, ScriptCompiler compiler, boolean ignoreMalformedByDefault, boolean coerceByDefault) {
super(name);
this.type = type;
this.scriptCompiler = Objects.requireNonNull(compiler);
this.ignoreMalformed
= Parameter.explicitBoolParam("ignore_malformed", true, m -> toType(m).ignoreMalformed, ignoreMalformedByDefault);
this.coerce
= Parameter.explicitBoolParam("coerce", true, m -> toType(m).coerce, coerceByDefault);
this.nullValue = new Parameter<>("null_value", false, () -> null,
(n, c, o) -> o == null ? null : type.parse(o, false), m -> toType(m).nullValue).acceptsNull();
this.dimension = Parameter.boolParam("dimension", false, m -> toType(m).dimension, false)
.addValidator(v -> {
if (v && EnumSet.of(NumberType.INTEGER, NumberType.LONG, NumberType.BYTE, NumberType.SHORT).contains(type) == false) {
throw new IllegalArgumentException("Parameter [dimension] cannot be set to numeric type [" + type.name + "]");
}
if (v && (indexed.getValue() == false || hasDocValues.getValue() == false)) {
throw new IllegalArgumentException(
"Field [dimension] requires that [" + indexed.name + "] and [" + hasDocValues.name + "] are true"
);
}
});
this.script.precludesParameters(ignoreMalformed, coerce, nullValue);
addScriptValidation(script, indexed, hasDocValues);
}
Builder nullValue(Number number) {
this.nullValue.setValue(number);
return this;
}
public Builder docValues(boolean hasDocValues) {
this.hasDocValues.setValue(hasDocValues);
return this;
}
private FieldValues<Number> scriptValues() {
if (this.script.get() == null) {
return null;
}
return type.compile(name, script.get(), scriptCompiler);
}
public Builder dimension(boolean dimension) {
this.dimension.setValue(dimension);
return this;
}
@Override
protected List<Parameter<?>> getParameters() {
return List.of(indexed, hasDocValues, stored, ignoreMalformed, coerce, nullValue, script, onScriptError, meta, dimension);
}
@Override
public NumberFieldMapper build(ContentPath contentPath) {
MappedFieldType ft = new NumberFieldType(buildFullName(contentPath), this);
return new NumberFieldMapper(name, ft, multiFieldsBuilder.build(this, contentPath), copyTo.build(), this);
}
}
public enum NumberType {
HALF_FLOAT("half_float", NumericType.HALF_FLOAT) {
@Override
public Float parse(Object value, boolean coerce) {
final float result = parseToFloat(value);
// Reduce the precision to what we actually index
return HalfFloatPoint.sortableShortToHalfFloat(HalfFloatPoint.halfFloatToSortableShort(result));
}
/**
* Parse a query parameter or {@code _source} value to a float,
* keeping float precision. Used by queries which need more
* precise control over their rounding behavior that
* {@link #parse(Object, boolean)} provides.
*/
private float parseToFloat(Object value) {
final float result;
if (value instanceof Number) {
result = ((Number) value).floatValue();
} else {
if (value instanceof BytesRef) {
value = ((BytesRef) value).utf8ToString();
}
result = Float.parseFloat(value.toString());
}
validateParsed(result);
return result;
}
@Override
public Number parsePoint(byte[] value) {
return HalfFloatPoint.decodeDimension(value, 0);
}
@Override
public Float parse(XContentParser parser, boolean coerce) throws IOException {
float parsed = parser.floatValue(coerce);
validateParsed(parsed);
return parsed;
}
@Override
public Query termQuery(String field, Object value) {
float v = parseToFloat(value);
return HalfFloatPoint.newExactQuery(field, v);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
float[] v = new float[values.size()];
int pos = 0;
for (Object value: values) {
v[pos++] = parseToFloat(value);
}
return HalfFloatPoint.newSetQuery(field, v);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
float l = Float.NEGATIVE_INFINITY;
float u = Float.POSITIVE_INFINITY;
if (lowerTerm != null) {
l = parseToFloat(lowerTerm);
if (includeLower) {
l = HalfFloatPoint.nextDown(l);
}
l = HalfFloatPoint.nextUp(l);
}
if (upperTerm != null) {
u = parseToFloat(upperTerm);
if (includeUpper) {
u = HalfFloatPoint.nextUp(u);
}
u = HalfFloatPoint.nextDown(u);
}
Query query = HalfFloatPoint.newRangeQuery(field, l, u);
if (hasDocValues) {
Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field,
HalfFloatPoint.halfFloatToSortableShort(l),
HalfFloatPoint.halfFloatToSortableShort(u));
query = new IndexOrDocValuesQuery(query, dvQuery);
}
return query;
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
List<Field> fields = new ArrayList<>();
if (indexed) {
fields.add(new HalfFloatPoint(name, value.floatValue()));
}
if (docValued) {
fields.add(new SortedNumericDocValuesField(name,
HalfFloatPoint.halfFloatToSortableShort(value.floatValue())));
}
if (stored) {
fields.add(new StoredField(name, value.floatValue()));
}
return fields;
}
private void validateParsed(float value) {
if (Float.isFinite(HalfFloatPoint.sortableShortToHalfFloat(HalfFloatPoint.halfFloatToSortableShort(value))) == false) {
throw new IllegalArgumentException("[half_float] supports only finite values, but got [" + value + "]");
}
}
},
FLOAT("float", NumericType.FLOAT) {
@Override
public Float parse(Object value, boolean coerce) {
final float result;
if (value instanceof Number) {
result = ((Number) value).floatValue();
} else {
if (value instanceof BytesRef) {
value = ((BytesRef) value).utf8ToString();
}
result = Float.parseFloat(value.toString());
}
validateParsed(result);
return result;
}
@Override
public Number parsePoint(byte[] value) {
return FloatPoint.decodeDimension(value, 0);
}
@Override
public Float parse(XContentParser parser, boolean coerce) throws IOException {
float parsed = parser.floatValue(coerce);
validateParsed(parsed);
return parsed;
}
@Override
public Query termQuery(String field, Object value) {
float v = parse(value, false);
return FloatPoint.newExactQuery(field, v);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
float[] v = new float[values.size()];
int pos = 0;
for (Object value: values) {
v[pos++] = parse(value, false);
}
return FloatPoint.newSetQuery(field, v);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
float l = Float.NEGATIVE_INFINITY;
float u = Float.POSITIVE_INFINITY;
if (lowerTerm != null) {
l = parse(lowerTerm, false);
if (includeLower == false) {
l = FloatPoint.nextUp(l);
}
}
if (upperTerm != null) {
u = parse(upperTerm, false);
if (includeUpper == false) {
u = FloatPoint.nextDown(u);
}
}
Query query = FloatPoint.newRangeQuery(field, l, u);
if (hasDocValues) {
Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field,
NumericUtils.floatToSortableInt(l),
NumericUtils.floatToSortableInt(u));
query = new IndexOrDocValuesQuery(query, dvQuery);
}
return query;
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
List<Field> fields = new ArrayList<>();
if (indexed) {
fields.add(new FloatPoint(name, value.floatValue()));
}
if (docValued) {
fields.add(new SortedNumericDocValuesField(name,
NumericUtils.floatToSortableInt(value.floatValue())));
}
if (stored) {
fields.add(new StoredField(name, value.floatValue()));
}
return fields;
}
private void validateParsed(float value) {
if (Float.isFinite(value) == false) {
throw new IllegalArgumentException("[float] supports only finite values, but got [" + value + "]");
}
}
},
DOUBLE("double", NumericType.DOUBLE) {
@Override
public Double parse(Object value, boolean coerce) {
double parsed = objectToDouble(value);
validateParsed(parsed);
return parsed;
}
@Override
public Number parsePoint(byte[] value) {
return DoublePoint.decodeDimension(value, 0);
}
@Override
public Double parse(XContentParser parser, boolean coerce) throws IOException {
double parsed = parser.doubleValue(coerce);
validateParsed(parsed);
return parsed;
}
@Override
public FieldValues<Number> compile(String fieldName, Script script, ScriptCompiler compiler) {
DoubleFieldScript.Factory scriptFactory = compiler.compile(script, DoubleFieldScript.CONTEXT);
return (lookup, ctx, doc, consumer) -> scriptFactory
.newFactory(fieldName, script.getParams(), lookup)
.newInstance(ctx)
.runForDoc(doc, consumer::accept);
}
@Override
public Query termQuery(String field, Object value) {
double v = parse(value, false);
return DoublePoint.newExactQuery(field, v);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
double[] v = values.stream().mapToDouble(value -> parse(value, false)).toArray();
return DoublePoint.newSetQuery(field, v);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
return doubleRangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, (l, u) -> {
Query query = DoublePoint.newRangeQuery(field, l, u);
if (hasDocValues) {
Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field,
NumericUtils.doubleToSortableLong(l),
NumericUtils.doubleToSortableLong(u));
query = new IndexOrDocValuesQuery(query, dvQuery);
}
return query;
});
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
List<Field> fields = new ArrayList<>();
if (indexed) {
fields.add(new DoublePoint(name, value.doubleValue()));
}
if (docValued) {
fields.add(new SortedNumericDocValuesField(name,
NumericUtils.doubleToSortableLong(value.doubleValue())));
}
if (stored) {
fields.add(new StoredField(name, value.doubleValue()));
}
return fields;
}
private void validateParsed(double value) {
if (Double.isFinite(value) == false) {
throw new IllegalArgumentException("[double] supports only finite values, but got [" + value + "]");
}
}
},
BYTE("byte", NumericType.BYTE) {
@Override
public Byte parse(Object value, boolean coerce) {
double doubleValue = objectToDouble(value);
if (doubleValue < Byte.MIN_VALUE || doubleValue > Byte.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a byte");
}
if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
return (byte) doubleValue;
}
@Override
public Number parsePoint(byte[] value) {
return INTEGER.parsePoint(value).byteValue();
}
@Override
public Short parse(XContentParser parser, boolean coerce) throws IOException {
int value = parser.intValue(coerce);
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a byte");
}
return (short) value;
}
@Override
public Query termQuery(String field, Object value) {
return INTEGER.termQuery(field, value);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
return INTEGER.termsQuery(field, values);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
return INTEGER.rangeQuery(field, lowerTerm, upperTerm, includeLower, includeUpper, hasDocValues, context);
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
return INTEGER.createFields(name, value, indexed, docValued, stored);
}
@Override
Number valueForSearch(Number value) {
return value.byteValue();
}
},
SHORT("short", NumericType.SHORT) {
@Override
public Short parse(Object value, boolean coerce) {
double doubleValue = objectToDouble(value);
if (doubleValue < Short.MIN_VALUE || doubleValue > Short.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a short");
}
if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
}
if (value instanceof Number) {
return ((Number) value).shortValue();
}
return (short) doubleValue;
}
@Override
public Number parsePoint(byte[] value) {
return INTEGER.parsePoint(value).shortValue();
}
@Override
public Short parse(XContentParser parser, boolean coerce) throws IOException {
return parser.shortValue(coerce);
}
@Override
public Query termQuery(String field, Object value) {
return INTEGER.termQuery(field, value);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
return INTEGER.termsQuery(field, values);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
return INTEGER.rangeQuery(field, lowerTerm, upperTerm, includeLower, includeUpper, hasDocValues, context);
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
return INTEGER.createFields(name, value, indexed, docValued, stored);
}
@Override
Number valueForSearch(Number value) {
return value.shortValue();
}
},
INTEGER("integer", NumericType.INT) {
@Override
public Integer parse(Object value, boolean coerce) {
double doubleValue = objectToDouble(value);
if (doubleValue < Integer.MIN_VALUE || doubleValue > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for an integer");
}
if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
return (int) doubleValue;
}
@Override
public Number parsePoint(byte[] value) {
return IntPoint.decodeDimension(value, 0);
}
@Override
public Integer parse(XContentParser parser, boolean coerce) throws IOException {
return parser.intValue(coerce);
}
@Override
public Query termQuery(String field, Object value) {
if (hasDecimalPart(value)) {
return Queries.newMatchNoDocsQuery("Value [" + value + "] has a decimal part");
}
int v = parse(value, true);
return IntPoint.newExactQuery(field, v);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
int[] v = new int[values.size()];
int upTo = 0;
for (Object value : values) {
if (hasDecimalPart(value) == false) {
v[upTo++] = parse(value, true);
}
}
if (upTo == 0) {
return Queries.newMatchNoDocsQuery("All values have a decimal part");
}
if (upTo != v.length) {
v = Arrays.copyOf(v, upTo);
}
return IntPoint.newSetQuery(field, v);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
int l = Integer.MIN_VALUE;
int u = Integer.MAX_VALUE;
if (lowerTerm != null) {
l = parse(lowerTerm, true);
// if the lower bound is decimal:
// - if the bound is positive then we increment it:
// if lowerTerm=1.5 then the (inclusive) bound becomes 2
// - if the bound is negative then we leave it as is:
// if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
if ((lowerTermHasDecimalPart == false && includeLower == false) ||
(lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
if (l == Integer.MAX_VALUE) {
return new MatchNoDocsQuery();
}
++l;
}
}
if (upperTerm != null) {
u = parse(upperTerm, true);
boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
if ((upperTermHasDecimalPart == false && includeUpper == false) ||
(upperTermHasDecimalPart && signum(upperTerm) < 0)) {
if (u == Integer.MIN_VALUE) {
return new MatchNoDocsQuery();
}
--u;
}
}
Query query = IntPoint.newRangeQuery(field, l, u);
if (hasDocValues) {
Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field, l, u);
query = new IndexOrDocValuesQuery(query, dvQuery);
if (context.indexSortedOnField(field)) {
query = new IndexSortSortedNumericDocValuesRangeQuery(field, l, u, query);
}
}
return query;
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
List<Field> fields = new ArrayList<>();
if (indexed) {
fields.add(new IntPoint(name, value.intValue()));
}
if (docValued) {
fields.add(new SortedNumericDocValuesField(name, value.intValue()));
}
if (stored) {
fields.add(new StoredField(name, value.intValue()));
}
return fields;
}
},
LONG("long", NumericType.LONG) {
@Override
public Long parse(Object value, boolean coerce) {
return objectToLong(value, coerce);
}
@Override
public Number parsePoint(byte[] value) {
return LongPoint.decodeDimension(value, 0);
}
@Override
public Long parse(XContentParser parser, boolean coerce) throws IOException {
return parser.longValue(coerce);
}
@Override
public FieldValues<Number> compile(String fieldName, Script script, ScriptCompiler compiler) {
final LongFieldScript.Factory scriptFactory = compiler.compile(script, LongFieldScript.CONTEXT);
return (lookup, ctx, doc, consumer) -> scriptFactory
.newFactory(fieldName, script.getParams(), lookup)
.newInstance(ctx)
.runForDoc(doc, consumer::accept);
}
@Override
public Query termQuery(String field, Object value) {
if (hasDecimalPart(value)) {
return Queries.newMatchNoDocsQuery("Value [" + value + "] has a decimal part");
}
long v = parse(value, true);
return LongPoint.newExactQuery(field, v);
}
@Override
public Query termsQuery(String field, Collection<?> values) {
long[] v = new long[values.size()];
int upTo = 0;
for (Object value : values) {
if (hasDecimalPart(value) == false) {
v[upTo++] = parse(value, true);
}
}
if (upTo == 0) {
return Queries.newMatchNoDocsQuery("All values have a decimal part");
}
if (upTo != v.length) {
v = Arrays.copyOf(v, upTo);
}
return LongPoint.newSetQuery(field, v);
}
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context) {
return longRangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, (l, u) -> {
Query query = LongPoint.newRangeQuery(field, l, u);
if (hasDocValues) {
Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field, l, u);
query = new IndexOrDocValuesQuery(query, dvQuery);
if (context.indexSortedOnField(field)) {
query = new IndexSortSortedNumericDocValuesRangeQuery(field, l, u, query);
}
}
return query;
});
}
@Override
public List<Field> createFields(String name, Number value,
boolean indexed, boolean docValued, boolean stored) {
List<Field> fields = new ArrayList<>();
if (indexed) {
fields.add(new LongPoint(name, value.longValue()));
}
if (docValued) {
fields.add(new SortedNumericDocValuesField(name, value.longValue()));
}
if (stored) {
fields.add(new StoredField(name, value.longValue()));
}
return fields;
}
};
private final String name;
private final NumericType numericType;
private final TypeParser parser;
NumberType(String name, NumericType numericType) {
this.name = name;
this.numericType = numericType;
this.parser = new TypeParser((n, c) -> new Builder(n, this, c.scriptCompiler(), c.getSettings()));
}
/** Get the associated type name. */
public final String typeName() {
return name;
}
/** Get the associated numeric type */
public final NumericType numericType() {
return numericType;
}
public final TypeParser parser() {
return parser;
}
public abstract Query termQuery(String field, Object value);
public abstract Query termsQuery(String field, Collection<?> values);
public abstract Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
boolean includeLower, boolean includeUpper,
boolean hasDocValues, SearchExecutionContext context);
public abstract Number parse(XContentParser parser, boolean coerce) throws IOException;
public abstract Number parse(Object value, boolean coerce);
public abstract Number parsePoint(byte[] value);
public abstract List<Field> createFields(String name, Number value, boolean indexed,
boolean docValued, boolean stored);
public FieldValues<Number> compile(String fieldName, Script script, ScriptCompiler compiler) {
// only implemented for long and double fields
throw new IllegalArgumentException("Unknown parameter [script] for mapper [" + fieldName + "]");
}
Number valueForSearch(Number value) {
return value;
}
/**
* Returns true if the object is a number and has a decimal part
*/
public static boolean hasDecimalPart(Object number) {
if (number instanceof Byte
|| number instanceof Short
|| number instanceof Integer
|| number instanceof Long) {
return false;
}
if (number instanceof Number) {
double doubleValue = ((Number) number).doubleValue();
return doubleValue % 1 != 0;
}
if (number instanceof BytesRef) {
number = ((BytesRef) number).utf8ToString();
}
if (number instanceof String) {
return Double.parseDouble((String) number) % 1 != 0;
}
return false;
}
/**
* Returns -1, 0, or 1 if the value is lower than, equal to, or greater than 0
*/
static double signum(Object value) {
if (value instanceof Number) {
double doubleValue = ((Number) value).doubleValue();
return Math.signum(doubleValue);
}
if (value instanceof BytesRef) {
value = ((BytesRef) value).utf8ToString();
}
return Math.signum(Double.parseDouble(value.toString()));
}
/**
* Converts an Object to a double by checking it against known types first
*/
public static double objectToDouble(Object value) {
double doubleValue;
if (value instanceof Number) {
doubleValue = ((Number) value).doubleValue();
} else if (value instanceof BytesRef) {
doubleValue = Double.parseDouble(((BytesRef) value).utf8ToString());
} else {
doubleValue = Double.parseDouble(value.toString());
}
return doubleValue;
}
/**
* Converts an Object to a {@code long} by checking it against known
* types and checking its range.
*/
public static long objectToLong(Object value, boolean coerce) {
if (value instanceof Long) {
return (Long)value;
}
double doubleValue = objectToDouble(value);
// this check does not guarantee that value is inside MIN_VALUE/MAX_VALUE because values up to 9223372036854776832 will
// be equal to Long.MAX_VALUE after conversion to double. More checks ahead.
if (doubleValue < Long.MIN_VALUE || doubleValue > Long.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a long");
}
if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
}
// longs need special handling so we don't lose precision while parsing
String stringValue = (value instanceof BytesRef) ? ((BytesRef) value).utf8ToString() : value.toString();
return Numbers.toLong(stringValue, coerce);
}
public static Query doubleRangeQuery(
Object lowerTerm,
Object upperTerm,
boolean includeLower,
boolean includeUpper,
BiFunction<Double, Double, Query> builder
) {
double l = Double.NEGATIVE_INFINITY;
double u = Double.POSITIVE_INFINITY;
if (lowerTerm != null) {
l = objectToDouble(lowerTerm);
if (includeLower == false) {
l = DoublePoint.nextUp(l);
}
}
if (upperTerm != null) {
u = objectToDouble(upperTerm);
if (includeUpper == false) {
u = DoublePoint.nextDown(u);
}
}
return builder.apply(l, u);
}
/**
* Processes query bounds into {@code long}s and delegates the
* provided {@code builder} to build a range query.
*/
public static Query longRangeQuery(
Object lowerTerm,
Object upperTerm,
boolean includeLower,
boolean includeUpper,
BiFunction<Long, Long, Query> builder
) {
long l = Long.MIN_VALUE;
long u = Long.MAX_VALUE;
if (lowerTerm != null) {
l = objectToLong(lowerTerm, true);
// if the lower bound is decimal:
// - if the bound is positive then we increment it:
// if lowerTerm=1.5 then the (inclusive) bound becomes 2
// - if the bound is negative then we leave it as is:
// if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
if ((lowerTermHasDecimalPart == false && includeLower == false) || (lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
if (l == Long.MAX_VALUE) {
return new MatchNoDocsQuery();
}
++l;
}
}
if (upperTerm != null) {
u = objectToLong(upperTerm, true);
boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
if ((upperTermHasDecimalPart == false && includeUpper == false) || (upperTermHasDecimalPart && signum(upperTerm) < 0)) {
if (u == Long.MIN_VALUE) {
return new MatchNoDocsQuery();
}
--u;
}
}
return builder.apply(l, u);
}
}
public static class NumberFieldType extends SimpleMappedFieldType {
private final NumberType type;
private final boolean coerce;
private final Number nullValue;
private final FieldValues<Number> scriptValues;
private final boolean isDimension;
public NumberFieldType(String name, NumberType type, boolean isSearchable, boolean isStored,
boolean hasDocValues, boolean coerce, Number nullValue, Map<String, String> meta,
FieldValues<Number> script, boolean isDimension) {
super(name, isSearchable, isStored, hasDocValues, TextSearchInfo.SIMPLE_MATCH_WITHOUT_TERMS, meta);
this.type = Objects.requireNonNull(type);
this.coerce = coerce;
this.nullValue = nullValue;
this.scriptValues = script;
this.isDimension = isDimension;
}
NumberFieldType(String name, Builder builder) {
this(name, builder.type, builder.indexed.getValue(), builder.stored.getValue(), builder.hasDocValues.getValue(),
builder.coerce.getValue().value(), builder.nullValue.getValue(), builder.meta.getValue(),
builder.scriptValues(), builder.dimension.getValue());
}
public NumberFieldType(String name, NumberType type) {
this(name, type, true, false, true, true, null, Collections.emptyMap(), null, false);
}
@Override
public String typeName() {
return type.name;
}
public NumericType numericType() {
return type.numericType();
}
@Override
public Query termQuery(Object value, SearchExecutionContext context) {
failIfNotIndexed();
return type.termQuery(name(), value);
}
@Override
public Query termsQuery(Collection<?> values, SearchExecutionContext context) {
failIfNotIndexed();
return type.termsQuery(name(), values);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper,
SearchExecutionContext context) {
failIfNotIndexed();
return type.rangeQuery(name(), lowerTerm, upperTerm, includeLower, includeUpper, hasDocValues(), context);
}
@Override
public Function<byte[], Number> pointReaderIfPossible() {
if (isSearchable()) {
return this::parsePoint;
}
return null;
}
@Override
public IndexFieldData.Builder fielddataBuilder(String fullyQualifiedIndexName, Supplier<SearchLookup> searchLookup) {
failIfNoDocValues();
return new SortedNumericIndexFieldData.Builder(name(), type.numericType());
}
@Override
public Object valueForDisplay(Object value) {
if (value == null) {
return null;
}
return type.valueForSearch((Number) value);
}
@Override
public ValueFetcher valueFetcher(SearchExecutionContext context, String format) {
if (format != null) {
throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] doesn't support formats.");
}
if (this.scriptValues != null) {
return FieldValues.valueFetcher(this.scriptValues, context);
}
return new SourceValueFetcher(name(), context, nullValue) {
@Override
protected Object parseSourceValue(Object value) {
if (value.equals("")) {
return nullValue;
}
return type.parse(value, coerce);
}
};
}
@Override
public DocValueFormat docValueFormat(String format, ZoneId timeZone) {
checkNoTimeZone(timeZone);
if (format == null) {
return DocValueFormat.RAW;
}
return new DocValueFormat.Decimal(format);
}
public Number parsePoint(byte[] value) {
return type.parsePoint(value);
}
@Override
public CollapseType collapseType() {
return CollapseType.NUMERIC;
}
/**
* @return true if field has been marked as a dimension field
*/
public boolean isDimension() {
return isDimension;
}
}
private final NumberType type;
private final boolean indexed;
private final boolean hasDocValues;
private final boolean stored;
private final Explicit<Boolean> ignoreMalformed;
private final Explicit<Boolean> coerce;
private final Number nullValue;
private final FieldValues<Number> scriptValues;
private final boolean ignoreMalformedByDefault;
private final boolean coerceByDefault;
private final boolean dimension;
private final ScriptCompiler scriptCompiler;
private final Script script;
private NumberFieldMapper(
String simpleName,
MappedFieldType mappedFieldType,
MultiFields multiFields,
CopyTo copyTo,
Builder builder) {
super(simpleName, mappedFieldType, multiFields, copyTo, builder.script.get() != null, builder.onScriptError.getValue());
this.type = builder.type;
this.indexed = builder.indexed.getValue();
this.hasDocValues = builder.hasDocValues.getValue();
this.stored = builder.stored.getValue();
this.ignoreMalformed = builder.ignoreMalformed.getValue();
this.coerce = builder.coerce.getValue();
this.nullValue = builder.nullValue.getValue();
this.ignoreMalformedByDefault = builder.ignoreMalformed.getDefaultValue().value();
this.coerceByDefault = builder.coerce.getDefaultValue().value();
this.scriptValues = builder.scriptValues();
this.dimension = builder.dimension.getValue();
this.scriptCompiler = builder.scriptCompiler;
this.script = builder.script.getValue();
}
boolean coerce() {
return coerce.value();
}
boolean ignoreMalformed() {
return ignoreMalformed.value();
}
@Override
public NumberFieldType fieldType() {
return (NumberFieldType) super.fieldType();
}
@Override
protected String contentType() {
return fieldType().type.typeName();
}
@Override
protected void parseCreateField(DocumentParserContext context) throws IOException {
Number value;
try {
value = value(context.parser(), type, nullValue, coerce.value());
} catch (InputCoercionException | IllegalArgumentException | JsonParseException e) {
if (ignoreMalformed.value() && context.parser().currentToken().isValue()) {
context.addIgnoredField(mappedFieldType.name());
return;
} else {
throw e;
}
}
if (value != null) {
indexValue(context, value);
}
}
private static Number value(XContentParser parser, NumberType numberType, Number nullValue, boolean coerce)
throws InputCoercionException, JsonParseException, IllegalArgumentException, IOException {
if (parser.currentToken() == Token.VALUE_NULL) {
return nullValue;
}
if (coerce && parser.currentToken() == Token.VALUE_STRING && parser.textLength() == 0) {
return nullValue;
}
return numberType.parse(parser, coerce);
}
private void indexValue(DocumentParserContext context, Number numericValue) {
List<Field> fields = fieldType().type.createFields(fieldType().name(), numericValue, indexed, hasDocValues, stored);
if (dimension) {
// Check that a dimension field is single-valued and not an array
if (context.doc().getByKey(fieldType().name()) != null) {
throw new IllegalArgumentException("Dimension field [" + fieldType().name() + "] cannot be a multi-valued field.");
}
if (fields.size() > 0) {
// Add the first field by key so that we can validate if it has been added
context.doc().addWithKey(fieldType().name(), fields.get(0));
context.doc().addAll(fields.subList(1, fields.size()));
}
} else {
context.doc().addAll(fields);
}
if (hasDocValues == false && (stored || indexed)) {
context.addToFieldNames(fieldType().name());
}
}
@Override
protected void indexScriptValues(SearchLookup searchLookup, LeafReaderContext readerContext, int doc,
DocumentParserContext documentParserContext) {
this.scriptValues.valuesForDoc(searchLookup, readerContext, doc, value -> indexValue(documentParserContext, value));
}
@Override
public FieldMapper.Builder getMergeBuilder() {
return new Builder(simpleName(), type, scriptCompiler, ignoreMalformedByDefault, coerceByDefault)
.dimension(dimension).init(this);
}
}
|
package io.spine.system.server;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.NullPointerTester;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.client.EntityStateWithVersion;
import io.spine.client.Query;
import io.spine.core.BoundedContextNames;
import io.spine.core.Command;
import io.spine.core.Event;
import io.spine.core.Subscribe;
import io.spine.server.BoundedContext;
import io.spine.server.event.AbstractEventSubscriber;
import io.spine.server.event.EventBus;
import io.spine.server.storage.memory.InMemoryStorageFactory;
import io.spine.system.server.given.client.ShoppingListAggregate;
import io.spine.system.server.given.client.ShoppingListRepository;
import io.spine.test.system.server.ListId;
import io.spine.test.system.server.ShoppingList;
import io.spine.testing.client.TestActorRequestFactory;
import io.spine.testing.server.TestEventFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.Optional;
import static com.google.common.testing.NullPointerTester.Visibility.PACKAGE;
import static io.spine.base.Identifier.newUuid;
import static io.spine.grpc.StreamObservers.noOpObserver;
import static io.spine.protobuf.AnyPacker.unpack;
import static io.spine.system.server.SystemBoundedContexts.systemOf;
import static io.spine.system.server.given.client.SystemClientTestEnv.findAggregate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisplayName("SystemReadSide should")
class DefaultSystemReadSideTest {
private static final TestEventFactory events =
TestEventFactory.newInstance(DefaultSystemReadSideTest.class);
private BoundedContext domainContext;
private SystemReadSide systemReadSide;
@BeforeEach
void setUp() {
domainContext = BoundedContext
.newBuilder()
.build();
systemReadSide = domainContext.systemClient().readSide();
}
@AfterEach
void tearDown() throws Exception {
domainContext.close();
}
@Test
@DisplayName("not allow nulls on construction")
void notAllowNullsOnConstruction() {
InMemoryStorageFactory storageFactory =
InMemoryStorageFactory.newInstance(BoundedContextNames.assumingTests(), false);
new NullPointerTester()
.setDefault(EventBus.class, EventBus
.newBuilder()
.setStorageFactory(storageFactory)
.build())
.testStaticMethods(DefaultSystemReadSide.class, PACKAGE);
}
@Test
@DisplayName("not allow nulls")
void notAllowNulls() {
new NullPointerTester()
.testAllPublicInstanceMethods(systemReadSide);
}
@Nested
class RegisterSystemEventDispatchers {
@Test
@DisplayName("pass system events to the domain")
void passSystemEvents() {
ProjectCreatedSubscriber subscriber = new ProjectCreatedSubscriber();
systemReadSide.register(subscriber);
EventMessage systemEvent = postSystemEvent();
Optional<EventMessage> receivedEvent = subscriber.lastEvent();
assertTrue(receivedEvent.isPresent());
EventMessage actualEvent = receivedEvent.get();
assertEquals(systemEvent, actualEvent);
}
@Test
@DisplayName("unregister dispatchers")
void unregisterDispatchers() {
ProjectCreatedSubscriber subscriber = new ProjectCreatedSubscriber();
systemReadSide.register(subscriber);
systemReadSide.unregister(subscriber);
postSystemEvent();
Optional<EventMessage> receivedEvent = subscriber.lastEvent();
assertFalse(receivedEvent.isPresent());
}
@CanIgnoreReturnValue
private EventMessage postSystemEvent() {
BoundedContext systemContext = systemOf(domainContext);
EventMessage systemEvent = SMProjectCreated
.newBuilder()
.setUuid(newUuid())
.setName("System Bus test project")
.build();
Event event = events.createEvent(systemEvent);
systemContext.eventBus().post(event);
return systemEvent;
}
}
@Nested
@DisplayName("read domain aggregate states")
class ReadDomainAggregates {
private final TestActorRequestFactory actorRequestFactory =
new TestActorRequestFactory(DefaultSystemWriteSideTest.class);
private ListId aggregateId;
@BeforeEach
void setUp() {
domainContext.register(new ShoppingListRepository());
aggregateId = ListId
.newBuilder()
.setId(newUuid())
.build();
createAggregate();
}
@Test
@DisplayName("by the given query")
void query() {
Query query =
actorRequestFactory.query()
.byIds(ShoppingList.class, ImmutableSet.of(aggregateId));
Iterator<EntityStateWithVersion> iterator = systemReadSide.readDomainAggregate(query);
EntityStateWithVersion next = iterator.next();
Message foundMessage = unpack(next.getState());
assertEquals(aggregate().state(), foundMessage);
assertEquals(aggregate().version(), next.getVersion());
}
private ShoppingListAggregate aggregate() {
return findAggregate(aggregateId, domainContext);
}
private void createAggregate() {
CreateShoppingList command = CreateShoppingList
.newBuilder()
.setId(aggregateId)
.build();
Command cmd = actorRequestFactory.createCommand(command);
domainContext.commandBus()
.post(cmd, noOpObserver());
}
}
/**
* A subscriber for {@link SMProjectCreated} events.
*
* <p>Memoizes the last received event and reports it on {@link #lastEvent()} calls.
*/
private static final class ProjectCreatedSubscriber extends AbstractEventSubscriber {
private EventMessage lastEvent;
@Subscribe
void on(SMProjectCreated event) {
lastEvent = event;
}
private Optional<EventMessage> lastEvent() {
return Optional.ofNullable(lastEvent);
}
}
}
|
package com.java110.api.listener.fee;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.fee.IFeeBMO;
import com.java110.api.listener.AbstractServiceApiDataFlowListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.core.smo.community.IParkingSpaceInnerServiceSMO;
import com.java110.core.smo.community.IRoomInnerServiceSMO;
import com.java110.core.smo.fee.IFeeAttrInnerServiceSMO;
import com.java110.core.smo.fee.IFeeConfigInnerServiceSMO;
import com.java110.core.smo.fee.IFeeInnerServiceSMO;
import com.java110.dto.fee.FeeAttrDto;
import com.java110.dto.fee.FeeDto;
import com.java110.dto.repair.RepairDto;
import com.java110.entity.center.AppService;
import com.java110.po.fee.PayFeePo;
import com.java110.po.owner.RepairPoolPo;
import com.java110.utils.constant.BusinessTypeConstant;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.constant.ServiceCodeConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @ClassName PayFeeListener
* @Description TODO
* @Author wuxw
* @Date 2019/6/3 13:46
* @Version 1.0
* add by wuxw 2019/6/3
**/
@Java110Listener("payFeeListener")
public class PayFeeListener extends AbstractServiceApiDataFlowListener {
private static Logger logger = LoggerFactory.getLogger(PayFeeListener.class);
@Autowired
private IFeeBMO feeBMOImpl;
@Autowired
private IParkingSpaceInnerServiceSMO parkingSpaceInnerServiceSMOImpl;
@Autowired
private IFeeInnerServiceSMO feeInnerServiceSMOImpl;
@Autowired
private IFeeAttrInnerServiceSMO feeAttrInnerServiceSMOImpl;
@Autowired
private IRoomInnerServiceSMO roomInnerServiceSMOImpl;
@Autowired
private IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl;
@Override
public String getServiceCode() {
return ServiceCodeConstant.SERVICE_CODE_PAY_FEE;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public void soService(ServiceDataFlowEvent event) {
logger.debug("ServiceDataFlowEvent : {}", event);
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
String paramIn = dataFlowContext.getReqData();
validate(paramIn);
JSONObject paramObj = JSONObject.parseObject(paramIn);
HttpHeaders header = new HttpHeaders();
dataFlowContext.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, "D");
JSONArray businesses = new JSONArray();
businesses.add(feeBMOImpl.addFeeDetail(paramObj, dataFlowContext));
businesses.add(feeBMOImpl.modifyFee(paramObj, dataFlowContext));
FeeAttrDto feeAttrDto = new FeeAttrDto();
feeAttrDto.setCommunityId(paramObj.getString("communityId"));
feeAttrDto.setFeeId(paramObj.getString("feeId"));
feeAttrDto.setSpecCd(FeeAttrDto.SPEC_CD_REPAIR);
List<FeeAttrDto> feeAttrDtos = feeAttrInnerServiceSMOImpl.queryFeeAttrs(feeAttrDto);
if (feeAttrDtos != null && feeAttrDtos.size() > 0) {
JSONObject business = JSONObject.parseObject("{\"datas\":{}}");
business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_REPAIR);
business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ + 1);
business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);
RepairPoolPo repairPoolPo = new RepairPoolPo();
repairPoolPo.setRepairId(feeAttrDtos.get(0).getValue());
repairPoolPo.setCommunityId(paramObj.getString("communityId"));
repairPoolPo.setState(RepairDto.STATE_APPRAISE);
business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(PayFeePo.class.getSimpleName(), JSONObject.toJSONString(repairPoolPo));
businesses.add(business);
}
ResponseEntity<String> responseEntity = feeBMOImpl.callService(dataFlowContext, service.getServiceCode(), businesses);
dataFlowContext.setResponseEntity(responseEntity);
}
/**
*
*
* @param paramIn "communityId": "7020181217000001",
* "memberId": "3456789",
* "memberTypeCd": "390001200001"
*/
private void validate(String paramIn) {
Assert.jsonObjectHaveKey(paramIn, "communityId", "communityId");
Assert.jsonObjectHaveKey(paramIn, "cycles", "cycles");
Assert.jsonObjectHaveKey(paramIn, "receivedAmount", "receivedAmount");
Assert.jsonObjectHaveKey(paramIn, "feeId", "feeId");
JSONObject paramInObj = JSONObject.parseObject(paramIn);
Assert.hasLength(paramInObj.getString("communityId"), "ID");
Assert.hasLength(paramInObj.getString("cycles"), "");
Assert.hasLength(paramInObj.getString("receivedAmount"), "");
Assert.hasLength(paramInObj.getString("feeId"), "ID");
FeeDto feeDto = new FeeDto();
feeDto.setFeeId(paramInObj.getString("feeId"));
feeDto.setCommunityId(paramInObj.getString("communityId"));
List<FeeDto> feeDtos = feeInnerServiceSMOImpl.queryFees(feeDto);
Assert.listOnlyOne(feeDtos, "ID");
feeDto = feeDtos.get(0);
if (FeeDto.STATE_FINISH.equals(feeDto.getState())) {
throw new IllegalArgumentException("");
}
}
@Override
public int getOrder() {
return DEFAULT_ORDER;
}
public IFeeInnerServiceSMO getFeeInnerServiceSMOImpl() {
return feeInnerServiceSMOImpl;
}
public void setFeeInnerServiceSMOImpl(IFeeInnerServiceSMO feeInnerServiceSMOImpl) {
this.feeInnerServiceSMOImpl = feeInnerServiceSMOImpl;
}
public IFeeConfigInnerServiceSMO getFeeConfigInnerServiceSMOImpl() {
return feeConfigInnerServiceSMOImpl;
}
public void setFeeConfigInnerServiceSMOImpl(IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl) {
this.feeConfigInnerServiceSMOImpl = feeConfigInnerServiceSMOImpl;
}
public IRoomInnerServiceSMO getRoomInnerServiceSMOImpl() {
return roomInnerServiceSMOImpl;
}
public void setRoomInnerServiceSMOImpl(IRoomInnerServiceSMO roomInnerServiceSMOImpl) {
this.roomInnerServiceSMOImpl = roomInnerServiceSMOImpl;
}
}
|
package com.kyanogen.signatureview;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.kyanogen.signatureview.model.Point;
public class SignatureView extends View {
public static final String TAG = SignatureView.class.getSimpleName();
private Canvas canvasBmp;
private boolean ignoreTouch;
private Point previousPoint, startPoint, currentPoint;
public static final float MIN_PEN_SIZE = 1f;
private static final float MIN_INCREMENT = 0.01f;
private static final float INCREMENT_CONSTANT = 0.0005f;
private static final float DRAWING_CONSTANT = 0.0085f;
public static final float MAX_VELOCITY_BOUND = 15f;
private static final float MIN_VELOCITY_BOUND = 1.6f;
private static final float STROKE_DES_VELOCITY = 1.0f;
private float VELOCITY_FILTER_WEIGHT = 0.2f;
private float lastVelocity, lastWidth;
private Paint paint, paintBm;
private Bitmap bmp;
private int layoutLeft, layoutTop, layoutRight, layoutBottom;
private Rect drawViewRect;
private int penColor, backgroundColor;
private boolean enableSignature;
private float penSize;
private Context context;
@SuppressWarnings("deprecation")
public SignatureView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.setWillNotDraw(false);
this.setDrawingCacheEnabled(true);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(
attrs,R.styleable.signature, 0, 0);
try {
backgroundColor = typedArray.getColor(R.styleable.signature_backgroundColor,
context.getResources().getColor(R.color.white));
penColor = typedArray.getColor(R.styleable.signature_penColor,
context.getResources().getColor(R.color.penRoyalBlue));
penSize = typedArray.getDimension(R.styleable.signature_penSize,
context.getResources().getDimension(R.dimen.pen_size));
enableSignature = typedArray.getBoolean(R.styleable.signature_enableSignature, true);
} finally {
typedArray.recycle();
}
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(penColor);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(penSize);
paintBm = new Paint(Paint.ANTI_ALIAS_FLAG);
paintBm.setAntiAlias(true);
paintBm.setStyle(Paint.Style.STROKE);
paintBm.setStrokeJoin(Paint.Join.ROUND);
paintBm.setStrokeCap(Paint.Cap.ROUND);
paintBm.setColor(Color.BLACK);
}
/**
* Get stoke size for signature creation
*
* @return float
*/
public float getPenSize() {
return penSize;
}
/**
* Set stoke size for signature creation
*
* @param penSize float
*/
public void setPenSize(float penSize) {
this.penSize = penSize;
}
/**
* Check if drawing on canvas is enabled or disabled
*
* @return boolean
*/
public boolean isEnableSignature() {
return enableSignature;
}
/**
* Enable or disable drawing on canvas
*
* @param enableSignature boolean
*/
public void setEnableSignature(boolean enableSignature) {
this.enableSignature = enableSignature;
}
/**
* Get stoke color for signature creation
*
* @return int
*/
public int getPenColor() {
return penColor;
}
/**
* Set stoke color for signature creation
*
* @param penColor int
*/
public void setPenColor(int penColor) {
this.penColor = penColor;
}
/**
* Get background color
*
* @return int
*/
public int getBackgroundColor() {
return backgroundColor;
}
/**
* Set background color
*
* @param backgroundColor int
*/
@Override
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
}
/**
* Clear signature from canvas
*
*/
public void clearCanvas(){
previousPoint=null;
startPoint=null;
currentPoint=null;
lastVelocity = 0;
lastWidth = 0;
newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom);
postInvalidate();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
layoutLeft = left;
layoutTop = top;
layoutRight = right;
layoutBottom = bottom;
if(bmp == null){
newBitmapCanvas(layoutLeft, layoutTop, layoutRight, layoutBottom);
}
}
private void newBitmapCanvas(int left, int top, int right, int bottom) {
bmp = null;
canvasBmp = null;
bmp = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888);
canvasBmp = new Canvas(bmp);
canvasBmp.drawColor(backgroundColor);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnableSignature()){
return false;
}
if(event.getPointerCount() > 1) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ignoreTouch = false;
drawViewRect = new Rect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom());
onTouchDownEvent(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
if(!drawViewRect.contains(getLeft() + (int) event.getX(), this.getTop() + (int) event.getY())){
//You are out of drawing area
if(!ignoreTouch){
ignoreTouch = true;
onTouchUpEvent(event.getX(), event.getY());
}
} else {
//You are in the drawing area
if(ignoreTouch){
ignoreTouch = false;
onTouchDownEvent(event.getX(), event.getY());
}else{
onTouchMoveEvent(event.getX(), event.getY());
}
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
onTouchUpEvent(event.getX(), event.getY());
break;
default:
break;
}
return true;// super.onTouchEvent(event);
}
private void onTouchDownEvent(float x, float y) {
previousPoint=null;
startPoint=null;
currentPoint=null;
lastVelocity = 0;
lastWidth = penSize;
currentPoint = new Point(x, y, System.currentTimeMillis());
previousPoint = currentPoint;
startPoint = previousPoint;
postInvalidate();
}
private void onTouchMoveEvent(float x, float y) {
if(previousPoint==null){
return;
}
startPoint = previousPoint;
previousPoint = currentPoint;
currentPoint = new Point(x, y, System.currentTimeMillis());
float velocity = currentPoint.velocityFrom(previousPoint);
velocity = VELOCITY_FILTER_WEIGHT * velocity + (1 - VELOCITY_FILTER_WEIGHT) * lastVelocity;
float strokeWidth = getStrokeWidth(velocity);
drawLine(lastWidth, strokeWidth, velocity);
lastVelocity = velocity;
lastWidth = strokeWidth;
postInvalidate();
}
private void onTouchUpEvent(float x, float y) {
if(previousPoint==null){
return;
}
startPoint = previousPoint;
previousPoint = currentPoint;
currentPoint = new Point(x, y, System.currentTimeMillis());
drawLine(lastWidth, 0, lastVelocity);
postInvalidate();
}
private float getStrokeWidth(float velocity){
return penSize - (velocity * STROKE_DES_VELOCITY);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bmp, 0, 0, paintBm);
}
private void drawLine(final float lastWidth, final float currentWidth,
final float velocity){
final Point mid1 = midPoint(previousPoint, startPoint);
final Point mid2 = midPoint(currentPoint, previousPoint);
draw(mid1, previousPoint, mid2, lastWidth,
currentWidth, velocity);
}
private float getPt( float n1 , float n2 , float perc){
float diff = n2 - n1;
return n1 + ( diff * perc );
}
private void draw(Point p0, Point p1, Point p2, float lastWidth,
float currentWidth, float velocity){
float xa, xb, ya, yb, x, y;
float increment;
if(velocity>MIN_VELOCITY_BOUND && velocity< MAX_VELOCITY_BOUND){
increment = DRAWING_CONSTANT - (velocity * INCREMENT_CONSTANT);
}else{
increment = MIN_INCREMENT;
}
for(float i = 0f; i < 1f; i += increment){
xa = getPt( p0.x , p1.x , i );
ya = getPt( p0.y , p1.y , i );
xb = getPt( p1.x , p2.x , i );
yb = getPt( p1.y , p2.y , i );
x = getPt( xa , xb , i );
y = getPt( ya , yb , i );
float strokeVal = lastWidth + (currentWidth - lastWidth) * (i);
paint.setStrokeWidth(strokeVal < MIN_PEN_SIZE ? MIN_PEN_SIZE : strokeVal);
canvasBmp.drawPoint(x, y, paint);
}
}
private Point midPoint(Point p1, Point p2){
return new Point((p1.x + p2.x) / 2.0f , (p1.y + p2.y) / 2, (p1.time + p2.time) / 2);
}
/**
* Get signature as bitmap
*
* @return Bitmap
*/
public Bitmap getSignatureBitmap(){
return Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), true);
}
/**
* Render bitmap in signature
*
* @param bitmap Bitmap
*/
public void setBitmap(Bitmap bitmap)
{
bmp=bitmap;
canvasBmp = new Canvas(bitmap);
postInvalidate();
}
/**
* Check is signature bitmap empty
*
* @return boolean
*/
public boolean isBitmapEmpty()
{
if(bmp!=null) {
Bitmap emptyBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
if (bmp.sameAs(emptyBitmap)) {
return true;}}
return false;
}
/**
* Get version info related to library
*
* @return String
*/
public String getVersionInfo(){
String versionInfo = null;
PackageInfo pInfo = null;
try {
pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if(pInfo!=null){
versionInfo = "SignatureView Version : "+pInfo.versionName;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionInfo;
}
}
|
package org.skyve.metadata.view.model.map;
import org.locationtech.jts.geom.Geometry;
public class MapFeature {
private Geometry geometry;
private boolean zoomable = true;
private boolean editable = false;
private String strokeColour;
private String fillColour;
private float fillOpacity = 1.0f;
private String iconRelativeFilePath;
private Integer iconAnchorX;
private Integer iconAnchorY;
public MapFeature() {
}
public MapFeature(Geometry geometry,
boolean zoomable,
boolean editable,
String strokeColour,
String fillColour,
float fillOpacity,
String iconRelativeFilePath,
Integer iconAnchorX,
Integer iconAnchorY) {
this.geometry = geometry;
this.zoomable = zoomable;
this.editable = editable;
this.strokeColour = strokeColour;
this.fillColour = fillColour;
setFillOpacity(fillOpacity);
this.iconRelativeFilePath = iconRelativeFilePath;
this.iconAnchorX = iconAnchorX;
this.iconAnchorY = iconAnchorY;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public boolean isZoomable() {
return zoomable;
}
public void setZoomable(boolean zoomable) {
this.zoomable = zoomable;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public String getStrokeColour() {
return strokeColour;
}
public void setStrokeColour(String strokeColour) {
this.strokeColour = strokeColour;
}
public String getFillColour() {
return fillColour;
}
public void setFillColour(String fillColour) {
this.fillColour = fillColour;
}
public float getFillOpacity() {
return fillOpacity;
}
/**
* Set the fill opacity of this map feature. Expects a float between 0.0 (fully transparent) and 1.0 (fully opaque).
*
* @param fillOpacity The fill opacity of the feature
*/
public void setFillOpacity(float fillOpacity) {
float value = fillOpacity;
if (fillOpacity > 1.0f) {
value = 1.0f;
}
if (fillOpacity < 0.0f) {
value = 0.0f;
}
this.fillOpacity = value;
}
public String getIconRelativeFilePath() {
return iconRelativeFilePath;
}
public void setIconRelativeFilePath(String iconRelativeFilePath) {
this.iconRelativeFilePath = iconRelativeFilePath;
}
public Integer getIconAnchorX() {
return iconAnchorX;
}
public void setIconAnchorX(Integer iconAnchorX) {
this.iconAnchorX = iconAnchorX;
}
public Integer getIconAnchorY() {
return iconAnchorY;
}
public void setIconAnchorY(Integer iconAnchorY) {
this.iconAnchorY = iconAnchorY;
}
}
|
package org.emerjoin.hi.web;
import org.emerjoin.hi.web.config.AppConfigurations;
import org.emerjoin.hi.web.i18n.I18nRuntime;
import org.emerjoin.hi.web.internal.JSCommandSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
//TODO: JavaDoc
@RequestScoped
public class FrontEnd {
public static String TEMPLATE_SESSION_VARIABLE ="$template_";
public static String LANGUAGE_SESSION_VARIABLE="$language_";
public static final String COMMAND_RELOAD = "reload";
public static final String COMMAND_RELOAD_LANGUAGE = "reloadLanguage";
public static final String COMMAND_REDIRECT = "redirect";
public static final String COMMAND_URL_PARAM = "url";
private Map<String,Map> laterInvocations = new HashMap<>();
@Inject
private HttpServletRequest httpServletRequest;
@Inject
private ActiveUser activeUser;
@Inject
private RequestContext requestContext;
@Inject
private AppContext appContext;
private String template;
private String language;
private Map<String,Object> templateData = new HashMap<>();
private Logger log = LoggerFactory.getLogger(FrontEnd.class);
@PostConstruct
private void onReady(){
this.language = AppConfigurations.get().getDefaultLanguage();
Object templateObject = activeUser.getProperty(TEMPLATE_SESSION_VARIABLE);
if(templateObject==null){
template=AppConfigurations.get().getDefaultTemplate();
activeUser.setProperty(TEMPLATE_SESSION_VARIABLE,template);
}else template = templateObject.toString();
Object langObject = activeUser.getProperty(LANGUAGE_SESSION_VARIABLE);
if(langObject==null){
language = AppConfigurations.get().getDefaultLanguage();
activeUser.setProperty(LANGUAGE_SESSION_VARIABLE,language);
}else language = langObject.toString();
}
public void refresh(){
invokeAfter(COMMAND_RELOAD, Collections.emptyMap());
}
public void refresh(String url){
Map<String,Object> map = new HashMap<>();
map.put(COMMAND_URL_PARAM,url);
invokeAfter(COMMAND_RELOAD, map);
}
public void submit(@Observes JSCommandSchedule jsCommandSchedule){
this.invokeAfter(jsCommandSchedule.getName(),
jsCommandSchedule.getParameters());
}
public void invokeAfter(String actionName, Map<String,Object> params) {
laterInvocations.put("$"+actionName,params);
}
@Deprecated
public void ajaxRedirect(String url){
Map map = new HashMap<>();
map.put(COMMAND_URL_PARAM,url);
invokeAfter(COMMAND_REDIRECT,map);
}
public void putOnTemplate(String key, Object value){
if(key==null||key.isEmpty())
throw new IllegalArgumentException("Key must not be null nor empty");
if(value==null)
throw new IllegalArgumentException("Value must not be null");
templateData.put(key,value);
}
public void setTemplateData(Map<String,Object> templateData) {
if(templateData==null)
throw new IllegalArgumentException("Template data Map must not be null");
this.templateData = templateData;
}
public void setLanguage(String name){
this.language = name;
activeUser.setProperty(LANGUAGE_SESSION_VARIABLE,this.language);
//Set reloadLanguage command if this method is invoked on an ajax request
if(isRequestAjax()||isFrontierRequest())
invokeAfter(COMMAND_RELOAD_LANGUAGE, Collections.emptyMap());
else {
if(I18nRuntime.isReady()){
I18nRuntime.get().setLanguage(name);
}
}
}
public void setTemplate(String template) {
String currentTemplate = activeUser.getProperty(TEMPLATE_SESSION_VARIABLE).toString();
if(template.equals(currentTemplate)) {
return;
}
log.debug(String.format("Template change [%s] => [%s]",currentTemplate,template));
this.template = template;
activeUser.setProperty(TEMPLATE_SESSION_VARIABLE,this.template);
//Reload command if this method is invoked on an ajax request
if(isRequestAjax()||isFrontierRequest()){
StringBuilder url = new StringBuilder();
url.append(appContext.getBaseURL());
url.append(requestContext.getRouteUrl());
String qs = httpServletRequest.getQueryString();
if(qs!=null && !qs.isEmpty()){
url.append("?");
url.append(httpServletRequest.getQueryString());
}
log.debug("Ajax Reload: "+url.toString());
refresh(url.toString());
}
}
public boolean wasTemplateDataSet(){
return templateData.size()>0;
}
public String getLanguage() {
return language;
}
public String getTemplate() {
return template;
}
public Map<String,Map> getLaterInvocations() {
return laterInvocations;
}
public Map<String,Object> getTemplateData() {
return templateData;
}
public boolean gotLaterInvocations() {
return laterInvocations.size()>0;
}
public boolean isRequestAjax(){
String headerValue = httpServletRequest.getHeader(RequestContext.AJAX_HEADER_KEY);
return headerValue!=null&&headerValue.equalsIgnoreCase("1");
}
public boolean isFrontierRequest(){
return httpServletRequest.getRequestURL().indexOf("jbind:")!=-1;
}
public String getLangDictionary(){
String dictPath = "/i18n/"+language+".json";
String dict = "{}";
try {
URL resource = httpServletRequest.getServletContext().getResource(dictPath);
if(resource==null)
return dict;
dict = Helper.readLines(resource.openStream(),null);
return dict;
}catch (Throwable ex){
return dict;
}
}
}
|
package es.tid.smartsteps.dispersion;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import es.tid.cosmos.base.mapreduce.CosmosJob;
/**
*
* @author dmicol
*/
public class Main extends Configured implements Tool {
private static final Logger LOGGER = Logger.getLogger(Main.class);
@Override
public int run(String[] args) throws Exception {
if (args.length != 5) {
throw new IllegalArgumentException(
"Usage: trafficCountsPath cellToMicrogridPath "
+ "microgridToPolygonPath soaCentroidsPath outputDir");
}
final Configuration config = Config.load(Config.class.getResource(
"/config.properties").openStream(), this.getConf());
final Path trafficCountsPath = new Path(args[0]);
final Path cellToMicrogridPath = new Path(args[1]);
final Path microgridToPolygonPath = new Path(args[2]);
final Path soaCentroidsPath = new Path(args[3]);
final Path outputDir = new Path(args[4]);
Path trafficCountsParsedPath = new Path(outputDir,
"traffic_counts_parsed");
{
CosmosJob job = CosmosJob.createMapJob(config,
"TrafficCountsParser",
TextInputFormat.class,
TrafficCountsParserMapper.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, trafficCountsPath);
FileOutputFormat.setOutputPath(job, trafficCountsParsedPath);
job.waitForCompletion(true);
}
boolean shouldFilterByDate = !config.get(Config.DATE_TO_FILTER).isEmpty();
Path trafficCountsParsedFilteredPath = new Path(outputDir,
"traffic_counts_parsed_filtered");
if (shouldFilterByDate) {
CosmosJob job = CosmosJob.createMapJob(config,
"DateFilter",
SequenceFileInputFormat.class,
DateFilterMapper.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, trafficCountsParsedPath);
FileOutputFormat.setOutputPath(job, trafficCountsParsedFilteredPath);
job.waitForCompletion(true);
}
Path cellToMicrogridParsedPath = new Path(outputDir,
"cell_to_microgrid_parsed");
{
CosmosJob job = CosmosJob.createMapJob(config,
"CellToMicrogridLookupParser",
TextInputFormat.class,
LookupParserMapper.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, cellToMicrogridPath);
FileOutputFormat.setOutputPath(job, cellToMicrogridParsedPath);
job.waitForCompletion(true);
}
Path countsByMicrogridPath = new Path(outputDir, "counts_by_microgrid");
{
CosmosJob job = CosmosJob.createMapReduceJob(config,
"CellToMicrogridEntryScaler",
SequenceFileInputFormat.class,
TrafficCountsScalerMapper.class,
TrafficCountsScalerReducer.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, shouldFilterByDate ?
trafficCountsParsedFilteredPath : trafficCountsParsedPath,
cellToMicrogridParsedPath);
FileOutputFormat.setOutputPath(job, countsByMicrogridPath);
job.waitForCompletion(true);
}
Path microgridToPolygonParsedPath = new Path(outputDir,
"microgrid_to_polygon_parsed");
{
CosmosJob job = CosmosJob.createMapJob(config,
"MicrogridToPolygonLookupParser",
TextInputFormat.class,
LookupParserMapper.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, microgridToPolygonPath);
FileOutputFormat.setOutputPath(job, microgridToPolygonParsedPath);
job.waitForCompletion(true);
}
Path countsByPolygonPath = new Path(outputDir, "counts_by_polygon");
{
CosmosJob job = CosmosJob.createMapReduceJob(config,
"MicrogridToPolygonEntryScaler",
SequenceFileInputFormat.class,
TrafficCountsScalerMapper.class,
TrafficCountsScalerReducer.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, countsByMicrogridPath,
microgridToPolygonParsedPath);
FileOutputFormat.setOutputPath(job, countsByPolygonPath);
job.waitForCompletion(true);
}
Path aggregatedCountsByPolygonPath = new Path(outputDir,
"aggregated_counts_by_polygon");
{
CosmosJob job = CosmosJob.createMapReduceJob(config,
"AggregationByCellIdAndDate",
SequenceFileInputFormat.class,
CellIdAndDateMapper.class,
AggregationReducer.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, countsByPolygonPath);
FileOutputFormat.setOutputPath(job, aggregatedCountsByPolygonPath);
job.waitForCompletion(true);
}
Path soaCentroidsParsedPath = new Path(outputDir, "soa_centroids_parsed");
{
CosmosJob job = CosmosJob.createMapJob(config,
"MicrogridToPolygonLookupParser",
TextInputFormat.class,
SOACentroidParserMapper.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, soaCentroidsPath);
FileOutputFormat.setOutputPath(job, soaCentroidsParsedPath);
job.waitForCompletion(true);
}
Path aggregatedCountsByPolygonJoinedPath = new Path(outputDir,
"soa_centroids_parsed_joined");
{
CosmosJob job = CosmosJob.createMapReduceJob(config,
"MicrogridToPolygonLookupParser",
SequenceFileInputFormat.class,
SOACentroidJoinerMapper.class,
SOACentroidJoinerReducer.class,
SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, aggregatedCountsByPolygonPath,
soaCentroidsParsedPath);
FileOutputFormat.setOutputPath(job,
aggregatedCountsByPolygonJoinedPath);
job.waitForCompletion(true);
}
Path aggregatedCountsByPolygonJoinedTextPath = new Path(outputDir,
"aggregated_counts_by_polygon_joined_text");
{
CosmosJob job = CosmosJob.createReduceJob(config,
"TrafficCountsJsonExporter",
SequenceFileInputFormat.class,
TrafficCountsJsonExporterReducer.class,
1,
TextOutputFormat.class);
FileInputFormat.setInputPaths(job,
aggregatedCountsByPolygonJoinedPath);
FileOutputFormat.setOutputPath(job,
aggregatedCountsByPolygonJoinedTextPath);
job.waitForCompletion(true);
}
return 0;
}
public static void main(String[] args) throws Exception {
try {
int res = ToolRunner.run(new Configuration(), new Main(), args);
if (res != 0) {
throw new Exception("Uknown error");
}
} catch (Exception ex) {
LOGGER.fatal(ex);
throw ex;
}
}
}
|
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.dto.particle.composition.CompositionBean;
import gov.nih.nci.cananolab.exception.BaseException;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.DateUtils;
import gov.nih.nci.cananolab.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Map.Entry;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.LabelValueBean;
/**
* This class sets up information required for all forms.
*
* @author pansu, cais
*
*/
public class InitSetup {
private InitSetup() {
}
public static InitSetup getInstance() {
return new InitSetup();
}
/**
* Queries and common_lookup table and creates a map in application context
*
* @param appContext
* @return
* @throws BaseException
*/
public Map<String, Map<String, SortedSet<String>>> getDefaultLookupTable(
ServletContext appContext) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = null;
if (appContext.getAttribute("defaultLookupTable") == null) {
defaultLookupTable = LookupService.findAllLookups();
appContext.setAttribute("defaultLookupTable", defaultLookupTable);
} else {
defaultLookupTable = new HashMap<String, Map<String, SortedSet<String>>>(
(Map<? extends String, Map<String, SortedSet<String>>>) appContext
.getAttribute("defaultLookupTable"));
}
return defaultLookupTable;
}
/**
* Retrieve lookup Map from lookup table and store in the application context
* @param appContext
* @param contextAttribute
* @param attributeName
* @return
* @throws BaseException
*/
public Map<String,Map<String, SortedSet<String>>> getLookupByAttribute(
ServletContext appContext, String contextAttribute,String attributeName) throws BaseException{
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
Map<String, Map<String, SortedSet<String>>> lookupByAttributeMap = new HashMap<String, Map<String, SortedSet<String>>>();
System.out.println("retrieving lookup by attribute");
Set<String> keySet = defaultLookupTable.keySet();
Iterator<String> key = keySet.iterator();
while(key.hasNext()){
String keyName = (String)key.next();
Map<String, SortedSet<String>> attributeMap = defaultLookupTable.get(keyName);
Set<String> keySet2 = attributeMap.keySet();
Iterator<String> iterator = keySet2.iterator();
while(iterator.hasNext()){
String attribute = (String)iterator.next();
if(attribute.equalsIgnoreCase(attributeName)){
String value = attributeMap.get(attribute).toString();
System.out.println("keyName: " + keyName + " attribute: " + attribute + " value: " + value);
Map<String, SortedSet<String>> nameLookup = null;
if (lookupByAttributeMap.get(keyName) != null) {
nameLookup = lookupByAttributeMap.get(keyName);
} else {
nameLookup = new HashMap<String, SortedSet<String>>();
lookupByAttributeMap.put(keyName, nameLookup);
}
SortedSet<String> values = null;
if (nameLookup.get(attribute) != null) {
values = nameLookup.get(attribute);
} else {
values = new TreeSet<String>();
nameLookup.put(attribute, values);
}
values.add(value);
}
}
}
appContext.setAttribute(contextAttribute, lookupByAttributeMap);
return lookupByAttributeMap;
}
/**
* Retrieve default lookup values from lookup table in the database and
* store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param lookupAttribute
* @return
* @throws BaseException
*/
public SortedSet<String> getDefaultTypesByLookup(ServletContext appContext,
String contextAttribute, String lookupName, String lookupAttribute)
throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
SortedSet<String> types = new TreeSet<String>();
if (defaultLookupTable.get(lookupName) != null) {
types = defaultLookupTable.get(lookupName).get(lookupAttribute);
appContext.setAttribute(contextAttribute, types);
return types;
} else {
return types;
}
}
/**
* Retrieve default lookup and other values from lookup table in the
* database and store in the session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws BaseException
*/
public SortedSet<String> getDefaultAndOtherTypesByLookup(
HttpServletRequest request, String sessionAttribute,
String lookupName, String lookupAttribute,
String otherTypeAttribute, boolean updateSession)
throws BaseException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.getDefaultAndOtherLookupTypes(lookupName,
lookupAttribute, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
/**
* Retrieve other values from lookup table in the database and store in the
* session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws BaseException
*/
public SortedSet<String> getOtherTypesByLookup(HttpServletRequest request,
String sessionAttribute, String lookupName,
String otherTypeAttribute, boolean updateSession)
throws BaseException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.findLookupValues(lookupName,
otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
/**
* Retrieve default lookup values by reflection and store in the app context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param fullParentClassName
* @return
* @throws Exception
*/
public SortedSet<String> getDefaultTypesByReflection(
ServletContext appContext, String contextAttribute,
String fullParentClassName) throws Exception {
SortedSet<String> types = new TreeSet<String>();
List<String> classNames = ClassUtils
.getChildClassNames(fullParentClassName);
for (String name : classNames) {
if (!name.contains("Other")) {
String shortClassName = ClassUtils.getShortClassName(name);
String displayName = ClassUtils.getDisplayName(shortClassName);
types.add(displayName);
}
}
appContext.setAttribute(contextAttribute, types);
return types;
}
/**
* Retrieve default lookup and other values by reflection and store in the
* session
*
* @param request
* @param contextAttributeForDefaults
* @param sessionAttribute
* @param fullParentClassName
* @param otherFullParentClassName
* @param updateSession
* @return
* @throws Exception
*/
public SortedSet<String> getDefaultAndOtherTypesByReflection(
HttpServletRequest request, String contextAttributeForDefaults,
String sessionAttribute, String fullParentClassName,
String otherFullParentClassName, boolean updateSession)
throws Exception {
ServletContext appContext = request.getSession().getServletContext();
SortedSet<String> defaultTypes = getDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
SortedSet<String> types = null;
if (updateSession) {
types = new TreeSet<String>(defaultTypes);
SortedSet<String> otherTypes = LookupService
.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null)
types.addAll(otherTypes);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
public String getFileUriFromFormFile(FormFile file, String folderType,
String sampleName, String submitType) {
if (file != null && !StringUtils.isEmpty(file.getFileName())) {
String prefix = folderType;
if (!StringUtils.isEmpty(sampleName)
&& !StringUtils.isEmpty(submitType)
&& folderType.equals(Constants.FOLDER_PARTICLE)) {
prefix += "/" + sampleName + "/";
prefix += StringUtils
.getOneWordLowerCaseFirstLetter(submitType);
}
String timestamp = DateUtils.convertDateToString(new Date(),
"yyyyMMdd_HH-mm-ss-SSS");
return prefix + "/" + timestamp + "_" + file.getFileName();
} else {
return null;
}
}
// check whether the value is already stored in context
private Boolean isLookupInContext(HttpServletRequest request,
String lookupName, String attribute, String otherAttribute,
String value) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(request
.getSession().getServletContext());
SortedSet<String> defaultValues = null;
if (defaultLookupTable.get(lookupName) != null) {
defaultValues = defaultLookupTable.get(lookupName).get(attribute);
}
if (defaultValues != null && defaultValues.contains(value)) {
return true;
} else {
SortedSet<String> otherValues = null;
if (defaultLookupTable.get(lookupName) != null) {
otherValues = defaultLookupTable.get(lookupName).get(
otherAttribute);
}
if (otherValues != null && otherValues.contains(value)) {
return true;
}
}
return false;
}
public void persistLookup(HttpServletRequest request, String lookupName,
String attribute, String otherAttribute, String value)
throws BaseException {
if (value == null || value.length() == 0) {
return;
}
if (isLookupInContext(request, lookupName, attribute, otherAttribute,
value)) {
return;
} else {
LookupService.saveOtherType(lookupName, otherAttribute, value);
}
}
/*public String getGridServiceUrl(HttpServletRequest request,
String gridHostName) throws Exception {
List<GridNodeBean> remoteNodes = getGridNodesInContext(request);
GridNodeBean theNode = GridService.getGridNodeByHostName(remoteNodes,
gridHostName);
if (theNode == null) {
throw new GridDownException("Grid node " + gridHostName
+ " is not available at this time.");
}
return theNode.getAddress();
}*/
/*public List<GridNodeBean> getGridNodesInContext(HttpServletRequest request)
throws Exception {
// URL localURL = new URL(request.getRequestURL().toString());
// int port = (localURL.getPort() == -1) ? 80 : localURL.getPort();
// String localGridURL = localURL.getProtocol() + "://"
// + localURL.getHost() + ":" + port + "/"
// + Constants.GRID_SERVICE_PATH;
// GridDiscoveryServiceJob gridDiscoveryJob = new
// GridDiscoveryServiceJob();
// List<GridNodeBean> gridNodes = gridDiscoveryJob.getAllGridNodes();
// GridNodeBean localGrid = GridService.getGridNodeByURL(gridNodes,
// localGridURL);
GridDiscoveryServiceJob gridDiscoveryJob = new GridDiscoveryServiceJob();
List<GridNodeBean> gridNodes = gridDiscoveryJob.getAllGridNodes();
List<GridNodeBean> remoteNodes = new ArrayList<GridNodeBean>(gridNodes);
for (GridNodeBean gridNode : gridNodes) {
if (gridNode.getHostName().equals(Constants.LOCAL_SITE)) {
remoteNodes.remove(gridNode);
}
}
Collections.sort(remoteNodes,
new Comparators.GridNodeHostNameComparator());
request.getSession().getServletContext().setAttribute("allGridNodes",
remoteNodes);
return gridNodes;
}*/
/*public PublicDataCountBean getPublicDataCountsInContext(
HttpServletRequest request) throws Exception {
PublicDataCountServiceJob dataCountJob = new PublicDataCountServiceJob();
PublicDataCountBean dataCounts = dataCountJob.getPublicDataCounts();
request.getSession().getServletContext().setAttribute(
"allPublicDataCounts", dataCounts);
return dataCounts;
}*/
public void updateCSMCleanupEntriesInContext(
List<String> csmEntriesToRemove, HttpServletRequest request)
throws Exception {
CSMCleanupJob job = new CSMCleanupJob();
Set<String> secureObjects = job.getAllSecureObjectsToRemove();
secureObjects.addAll(csmEntriesToRemove);
request.getSession().getServletContext().setAttribute(
"allCSMEntriesToRemove", secureObjects);
}
public List<LabelValueBean> getDefaultAndOtherTypesByLookupAsOptions(
String lookupName, String lookupAttribute, String otherTypeAttribute)
throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultValues = LookupService.findLookupValues(
lookupName, lookupAttribute);
// annotate the label of the default ones with *s.
for (String name : defaultValues) {
LabelValueBean lv = new LabelValueBean(name, name);
lvBeans.add(lv);
}
SortedSet<String> otherValues = LookupService.findLookupValues(
lookupName, otherTypeAttribute);
for (String name : otherValues) {
LabelValueBean lv = new LabelValueBean("[" + name + "]", name);
lvBeans.add(lv);
}
return lvBeans;
}
public List<LabelValueBean> getDefaultAndOtherTypesByReflectionAsOptions(
ServletContext appContext, String contextAttributeForDefaults,
String fullParentClassName, String otherFullParentClassName)
throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultTypes = getDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
for (String type : defaultTypes) {
LabelValueBean lv = new LabelValueBean(type, type);
lvBeans.add(lv);
}
SortedSet<String> otherTypes = LookupService
.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null) {
for (String type : otherTypes) {
LabelValueBean lv = new LabelValueBean("[" + type + "]", type);
lvBeans.add(lv);
}
}
return lvBeans;
}
public void setStaticOptions(ServletContext appContext) {
LabelValueBean[] booleanOptions = new LabelValueBean[] {
new LabelValueBean("true", "1"),
new LabelValueBean("false", "0") };
appContext.setAttribute("booleanOptions", booleanOptions);
LabelValueBean[] stringOperands = new LabelValueBean[] {
new LabelValueBean(Constants.STRING_OPERAND_CONTAINS,
Constants.STRING_OPERAND_CONTAINS),
new LabelValueBean(Constants.STRING_OPERAND_EQUALS,
Constants.STRING_OPERAND_EQUALS) };
appContext.setAttribute("stringOperands", stringOperands);
LabelValueBean[] booleanOperands = new LabelValueBean[] { new LabelValueBean(
"equals", "is") };
appContext.setAttribute("booleanOperands", booleanOperands);
LabelValueBean[] numberOperands = new LabelValueBean[] {
new LabelValueBean("=", "="), new LabelValueBean(">", ">"),
new LabelValueBean(">=", ">="), new LabelValueBean("<", "<"),
new LabelValueBean("<=", "<=") };
appContext.setAttribute("numberOperands", numberOperands);
appContext.setAttribute("allCompositionSections",
CompositionBean.ALL_COMPOSITION_SECTIONS);
//register page
LabelValueBean[] titleOperands = new LabelValueBean[]{
new LabelValueBean(" "," "),
new LabelValueBean("Dr.","Dr."),
new LabelValueBean("Mr.", "Mr.") ,
new LabelValueBean("Mrs.", "Mrs."),
new LabelValueBean("Miss", "Miss"),
new LabelValueBean("Ms.", "Ms.")};
appContext.setAttribute("titleOperands", titleOperands);
}
}
|
package gov.nih.nci.evs.browser.utils;
import java.io.*;
import java.util.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.HashSet;
import java.util.Arrays;
import javax.faces.model.SelectItem;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms;
import org.LexGrid.concepts.Concept;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeRenderingList;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ModuleDescriptionList;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.ModuleDescription;
import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.concepts.Definition;
import org.LexGrid.concepts.Comment;
import org.LexGrid.concepts.Presentation;
import org.apache.log4j.Logger;
import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException;
import org.LexGrid.LexBIG.Exceptions.LBInvocationException;
import org.LexGrid.LexBIG.Utility.ConvenienceMethods;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.commonTypes.Property;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.ActiveOption;
import org.LexGrid.LexBIG.Utility.ConvenienceMethods;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.commonTypes.Property;
import org.LexGrid.concepts.Concept;
import org.LexGrid.relations.Relations;
import org.LexGrid.commonTypes.PropertyQualifier;
import org.LexGrid.commonTypes.Source;
import org.LexGrid.naming.SupportedSource;
import org.LexGrid.naming.SupportedPropertyQualifier;
import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus;
import org.LexGrid.naming.SupportedAssociation;
import org.LexGrid.naming.SupportedAssociationQualifier;
import org.LexGrid.naming.SupportedProperty;
import org.LexGrid.naming.SupportedPropertyQualifier;
import org.LexGrid.naming.SupportedRepresentationalForm;
import org.LexGrid.naming.SupportedSource;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.naming.Mappings;
import org.LexGrid.naming.SupportedHierarchy;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.RenderingDetail;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeTagList;
import gov.nih.nci.evs.browser.properties.NCImBrowserProperties;
import org.LexGrid.LexBIG.Exceptions.LBParameterException;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms;
import org.LexGrid.concepts.Entity;
/**
* @author EVS Team
* @version 1.0
*
* Modification history
* Initial implementation kim.ong@ngc.com
*
*/
public class DataUtils {
private static Vector<String> sourceListData = null;
LocalNameList noopList_ = Constructors.createLocalNameList("_noop_");
static SortOptionList sortByCode_ = Constructors.createSortOptionList(new String[] {"code"});
int maxReturn = 5000;
Connection con;
Statement stmt;
ResultSet rs;
private List supportedStandardReportList = new ArrayList();
private static List standardReportTemplateList = null;
private static List adminTaskList = null;
private static List userTaskList = null;
private static List propertyTypeList = null;
private static List _ontologies = null;
private static org.LexGrid.LexBIG.LexBIGService.LexBIGService lbSvc = null;
public org.LexGrid.LexBIG.Utility.ConvenienceMethods lbConvMethods = null;
public CodingSchemeRenderingList csrl = null;
private Vector supportedCodingSchemes = null;
private static HashMap codingSchemeMap = null;
private Vector codingSchemes = null;
private static HashMap csnv2codingSchemeNameMap = null;
private static HashMap csnv2VersionMap = null;
private static List directionList = null;
// For customized query use
public static int ALL = 0;
public static int PREFERRED_ONLY = 1;
public static int NON_PREFERRED_ONLY = 2;
static int RESOLVE_SOURCE = 1;
static int RESOLVE_TARGET = -1;
static int RESTRICT_SOURCE = -1;
static int RESTRICT_TARGET = 1;
public static final int SEARCH_NAME_CODE = 1;
public static final int SEARCH_DEFINITION = 2;
public static final int SEARCH_PROPERTY_VALUE = 3;
public static final int SEARCH_ROLE_VALUE = 6;
public static final int SEARCH_ASSOCIATION_VALUE = 7;
static final List<String> STOP_WORDS = Arrays.asList(new String[] {
"a", "an", "and", "by", "for", "of", "on", "in", "nos", "the", "to", "with"});
public static String TYPE_ROLE = "type_role";
public static String TYPE_ASSOCIATION = "type_association";
public static String TYPE_SUPERCONCEPT = "type_superconcept";
public static String TYPE_SUBCONCEPT = "type_subconcept";
public String NCICBContactURL = null;
public String terminologySubsetDownloadURL = null;
public String NCIMBuildInfo = null;
static String[] hierAssocToParentNodes_ = new String[] { "PAR", "isa", "branch_of", "part_of", "tributary_of" };
static String[] hierAssocToChildNodes_ = new String[] { "CHD", "hasSubtype" };
public DataUtils()
{
}
/*
public static List getOntologyList() {
if(_ontologies == null) setCodingSchemeMap();
return _ontologies;
}
*/
/*
public static Vector<String> getSupportedAssociationNames(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
return getSupportedAssociationNames(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getSupportedAssociationNames(codingSchemeName, version);
}
*/
public static Vector<String> getSupportedAssociationNames(String codingSchemeName, String version)
{
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null)
{
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) {
System.out.println("scheme is NULL");
return null;
}
Vector<String> v = new Vector<String>();
SupportedAssociation[] assos = scheme.getMappings().getSupportedAssociation();
for (int i=0; i<assos.length; i++)
{
SupportedAssociation sa = (SupportedAssociation) assos[i];
v.add(sa.getLocalId());
}
return v;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/*
public static Vector<String> getPropertyNameListData(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null)
{
return null;
}
String version = (String) csnv2VersionMap.get(key);
if(version == null)
{
return null;
}
return getPropertyNameListData(codingSchemeName, version);
}
*/
public static Vector<String> getPropertyNameListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedProperty[] properties = scheme.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty property = properties[i];
propertyNameListData.add(property.getLocalId());
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String getCodingSchemeName(String key)
{
return (String) csnv2codingSchemeNameMap.get(key);
}
public static String getCodingSchemeVersion(String key)
{
return (String) csnv2VersionMap.get(key);
}
public static Vector<String> getRepresentationalFormListData(String key)
{
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getRepresentationalFormListData(codingSchemeName, version);
}
public static Vector<String> getRepresentationalFormListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedRepresentationalForm[] forms = scheme.getMappings().getSupportedRepresentationalForm();
if (forms != null)
{
for (int i=0; i<forms.length; i++)
{
SupportedRepresentationalForm form = forms[i];
propertyNameListData.add(form.getLocalId());
}
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getPropertyQualifierListData(String key)
{
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getPropertyQualifierListData(codingSchemeName, version);
}
public static Vector<String> getPropertyQualifierListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyQualifierListData = new Vector<String>();
SupportedPropertyQualifier[] qualifiers = scheme.getMappings().getSupportedPropertyQualifier();
for (int i=0; i<qualifiers.length; i++)
{
SupportedPropertyQualifier qualifier = qualifiers[i];
propertyQualifierListData.add(qualifier.getLocalId());
}
return propertyQualifierListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/*
public static Vector<String> getSourceListData(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
return getSourceListData(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getSourceListData(codingSchemeName, version);
}
*/
public static Vector<String> getSourceListData(String codingSchemeName, String version) {
if (sourceListData != null) return sourceListData;
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
sourceListData = new Vector<String>();
sourceListData.add("ALL");
//Insert your code here
SupportedSource[] sources = scheme.getMappings().getSupportedSource();
for (int i=0; i<sources.length; i++)
{
SupportedSource source = sources[i];
sourceListData.add(source.getLocalId());
}
return sourceListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String int2String(Integer int_obj) {
if (int_obj == null)
{
return null;
}
String retstr = Integer.toString(int_obj);
return retstr;
}
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (vers != null) versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
} catch (Exception e1) {
//e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
// Analyze the result ...
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
}
} catch (Exception e) {
//e.printStackTrace();
return null;
}
return null;
}
public static CodedNodeSet restrictToSource(CodedNodeSet cns, String source) {
if (cns == null) return cns;
if (source == null || source.compareTo("*") == 0 || source.compareTo("") == 0 || source.compareTo("ALL") == 0) return cns;
LocalNameList contextList = null;
LocalNameList sourceLnL = null;
NameAndValueList qualifierList = null;
Vector<String> w2 = new Vector<String>();
w2.add(source);
sourceLnL = vector2LocalNameList(w2);
LocalNameList propertyLnL = null;
CodedNodeSet.PropertyType[] types = new PropertyType[] {PropertyType.PRESENTATION};
try {
cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList);
} catch (Exception ex) {
System.out.println("restrictToSource throws exceptions.");
return null;
}
return cns;
}
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code, String source)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (vers != null) versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
} catch (Exception e1) {
//e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
cns = restrictToSource(cns, source);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
// Analyze the result ...
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
}
} catch (Exception e) {
//e.printStackTrace();
return null;
}
return null;
}
public static NameAndValueList createNameAndValueList(String[] names, String[] values)
{
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.length; i++)
{
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null)
{
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator)
{
return iterator.getNext();
}
public Vector getParentCodes(String scheme, String version, String code) {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0)
{
return null;
}
String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
//KLO, 01/23/2009
//Vector<Concept> superconcept_vec = util.getAssociationSources(scheme, version, code, hierarchicalAssoName);
Vector superconcept_vec = getAssociationSourceCodes(scheme, version, code, hierarchicalAssoName);
if (superconcept_vec == null) return null;
//SortUtils.quickSort(superconcept_vec, SortUtils.SORT_BY_CODE);
return superconcept_vec;
}
public Vector getAssociationSourceCodes(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
false, true, 1, 1, new LocalNameList(), null, null, maxReturn);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList targetof = ref.getTargetOf();
Association[] associations = targetof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
//KLO
assoc = processForAnonomousNodes(assoc);
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
v.add(ac.getReferencedEntry().getEntityCode());
}
}
}
SortUtils.quickSort(v);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName)
{
if (codes == null)
{
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++)
{
ConceptReference cr = new ConceptReference();
cr.setCodingSchemeName(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public Vector getSubconceptCodes(String scheme, String version, String code) { //throws LBException{
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = null;
associations = null;
try {
associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null);
} catch (Exception e) {
System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext ");
return v;
}
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
//ex.printStackTrace();
}
return v;
}
public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationNames();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
public static String getFileName(String pathname) {
File file = new File(pathname);
String filename = file.getName();
return filename;
}
protected static Association processForAnonomousNodes(Association assoc){
//clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
//Conditionals to deal with anonymous nodes and UMLS top nodes "V-X"
//The first three allow UMLS traversal to top node.
//The last two are specific to owl anonymous nodes which can act like false
//top nodes.
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
//do nothing
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
protected static CodingScheme getCodingScheme(String codingScheme,
CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static Vector<SupportedProperty> getSupportedProperties(CodingScheme cs)
{
if (cs == null) return null;
Vector<SupportedProperty> v = new Vector<SupportedProperty>();
SupportedProperty[] properties = cs.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty sp = (SupportedProperty) properties[i];
v.add(sp);
}
return v;
}
public static Vector<String> getSupportedPropertyNames(CodingScheme cs)
{
Vector w = getSupportedProperties(cs);
if (w == null) return null;
Vector<String> v = new Vector<String>();
for (int i=0; i<w.size(); i++)
{
SupportedProperty sp = (SupportedProperty) w.elementAt(i);
v.add(sp.getLocalId());
}
return v;
}
public static Vector<String> getSupportedPropertyNames(String codingScheme, String version)
{
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
CodingScheme cs = getCodingScheme(codingScheme, versionOrTag);
return getSupportedPropertyNames(cs);
} catch (Exception ex) {
}
return null;
}
public static Vector getPropertyNamesByType(Concept concept, String property_type) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
//v.add(p.getValue().getContent());
v.add(p.getPropertyName());
}
return v;
}
public static Vector getPropertyValues(Concept concept, String property_type, String property_name) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
else
{
System.out.println("WARNING: property_type not found -- " + property_type);
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
if (property_name.compareTo(p.getPropertyName()) == 0)
{
String t = p.getValue().getContent();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
t = t + "|" + src.getContent();
}
v.add(t);
}
}
return v;
}
public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
List list = new ArrayList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i=0; i<relations.length; i++)
{
Relations relation = relations[i];
if (relation.getContainerName().compareToIgnoreCase("roles") == 0)
{
org.LexGrid.relations.Association[] asso_array = relation.getAssociation();
for (int j=0; j<asso_array.length; j++)
{
org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j];
list.add(association.getAssociationName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public static void sortArray(ArrayList list) {
String tmp;
if (list.size() <= 1) return;
for (int i = 0; i < list.size(); i++) {
String s1 = (String) list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String s2 = (String) list.get(j);
if(s1.compareToIgnoreCase(s2 ) > 0 ) {
tmp = s1;
list.set(i, s2);
list.set(j, tmp);
}
}
}
}
public static void sortArray(String[] strArray) {
String tmp;
if (strArray.length <= 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if(strArray[i].compareToIgnoreCase(strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public String[] getSortedKeys(HashMap map)
{
if (map == null) return null;
Set keyset = map.keySet();
String[] names = new String[keyset.size()];
Iterator it = keyset.iterator();
int i = 0;
while (it.hasNext())
{
String s = (String) it.next();
names[i] = s;
i++;
}
sortArray(names);
return names;
}
public String getPreferredName(Concept c) {
Presentation[] presentations = c.getPresentation();
for (int i=0; i<presentations.length; i++)
{
Presentation p = presentations[i];
if (p.getPropertyName().compareTo("Preferred_Name") == 0)
{
return p.getValue().getContent();
}
}
return null;
}
public HashMap getRelationshipHashMap(String scheme, String version, String code)
{
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
ArrayList roleList = new ArrayList();
ArrayList associationList = new ArrayList();
ArrayList superconceptList = new ArrayList();
ArrayList subconceptList = new ArrayList();
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd,
// !associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, noopList_, null, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
//System.out.println("\t" + assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName))
{
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null) name = ed.getContent();
//String pt = getPreferredName(ac.getReferencedEntry());
String pt = name;
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
//printAssocation(scheme, version, code, assoc.getAssociationName(), ac.getConceptCode());
String s = associationName + "|" + pt + "|" + ac.getConceptCode();
if (!parent_asso_vec.contains(associationName) &&
!child_asso_vec.contains(associationName)) {
if (isRole)
{
if (associationName.compareToIgnoreCase("hasSubtype") != 0)
{
//System.out.println("Adding role: " + s);
roleList.add(s);
}
}
else
{
//System.out.println("Adding association: " + s);
associationList.add(s);
}
}
}
}
}
}
}
if (roleList.size() > 0) {
//Collections.sort(roleList);
SortUtils.quickSort(roleList);
}
if (associationList.size() > 0) {
//Collections.sort(associationList);
SortUtils.quickSort(associationList);
}
map.put(TYPE_ROLE, roleList);
map.put(TYPE_ASSOCIATION, associationList);
Vector superconcept_vec = getSuperconcepts(scheme, version, code);
for (int i=0; i<superconcept_vec.size(); i++)
{
Concept c = (Concept) superconcept_vec.elementAt(i);
String pt = c.getEntityDescription().getContent();
superconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(superconceptList);
map.put(TYPE_SUPERCONCEPT, superconceptList);
Vector subconcept_vec = getSubconcepts(scheme, version, code);
for (int i=0; i<subconcept_vec.size(); i++)
{
Concept c = (Concept) subconcept_vec.elementAt(i);
String pt = c.getEntityDescription().getContent();
subconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(subconceptList);
map.put(TYPE_SUBCONCEPT, subconceptList);
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
return getAssociationSources(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
return getAssociationTargets(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
//Constructors.createSortOptionList(new String[]{"matchToQuery", "code"});
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry();
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getEntityCode().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static Vector<String> parseData(String line, String tab)
{
Vector data_vec = new Vector();
StringTokenizer st = new StringTokenizer(line, tab);
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (value.compareTo("null") == 0) value = " ";
data_vec.add(value);
}
return data_vec;
}
public static String getHyperlink(String url, String codingScheme, String code)
{
codingScheme = codingScheme.replace(" ", "%20");
String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code;
return link;
}
public List getHierarchyRoots(
String scheme,
String version,
String hierarchyID) throws LBException
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
return getHierarchyRoots(scheme, csvt, hierarchyID);
}
public List getHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException
{
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
}
public List getSourceHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String sab) throws LBException
{
/*
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
*/
ResolvedConceptReferenceList roots = null;
try {
roots = new MetaTreeUtils().getSourceRoots(sab);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
} catch (Exception ex) {
}
return new ArrayList();
}
public List ResolvedConceptReferenceList2List(ResolvedConceptReferenceList rcrl)
{
ArrayList list = new ArrayList();
for (int i=0; i<rcrl.getResolvedConceptReferenceCount(); i++)
{
ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i);
list.add(rcr);
}
return list;
}
public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, sab);
}
public static Vector getSynonyms(String scheme, String version, String tag, String code) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept) {
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept, String sab) {
if (concept == null) return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
for (int i=0; i<properties.length; i++)
{
Presentation p = properties[i];
// name
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
// source-code
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null)
{
for (int j=0; j<qualifiers.length; j++)
{
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0)
{
term_source_code = qualifier_value;
break;
}
}
}
// term type
term_type = p.getRepresentationalForm();
// source
Source[] sources = p.getSource();
if (sources != null && sources.length > 0)
{
Source src = sources[0];
term_source = src.getContent();
}
if (sab == null) {
v.add(term_name + "|" + term_type + "|" + term_source + "|" + term_source_code);
} else if (term_source != null && sab.compareTo(term_source) == 0) {
v.add(term_name + "|" + term_type + "|" + term_source + "|" + term_source_code);
}
}
SortUtils.quickSort(v);
return v;
}
public String getNCICBContactURL()
{
if (NCICBContactURL != null)
{
return NCICBContactURL;
}
String default_url = "ncicb@pop.nci.nih.gov";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCICBContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL);
if (NCICBContactURL == null)
{
NCICBContactURL = default_url;
}
} catch (Exception ex) {
}
System.out.println("getNCICBContactURL returns " + NCICBContactURL);
return NCICBContactURL;
}
public String getTerminologySubsetDownloadURL()
{
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
terminologySubsetDownloadURL = properties.getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL);
} catch (Exception ex) {
}
return terminologySubsetDownloadURL;
}
public String getNCIMBuildInfo()
{
if (NCIMBuildInfo != null)
{
return NCIMBuildInfo;
}
String default_info = "N/A";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCIMBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO);
if (NCIMBuildInfo == null)
{
NCIMBuildInfo = default_info;
}
} catch (Exception ex) {
}
System.out.println("getNCIMBuildInfo returns " + NCIMBuildInfo);
return NCIMBuildInfo;
}
public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) {
Vector<String> v = new Vector<String>();
v.add("String");
v.add("Code");
v.add("CUI");
return v;
}
public static Vector getSources(String scheme, String version, String tag, String code) {
Vector sources = getSynonyms(scheme, version, tag, code);
//GLIOBLASTOMA MULTIFORME|DI|DXP|U000721
HashSet hset = new HashSet();
Vector source_vec = new Vector();
for (int i=0; i<sources.size(); i++)
{
String s = (String) sources.elementAt(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String name = (String) ret_vec.elementAt(0);
String type = (String) ret_vec.elementAt(1);
String src = (String) ret_vec.elementAt(2);
String srccode = (String) ret_vec.elementAt(3);
if (!hset.contains(src)) {
hset.add(src);
source_vec.add(src);
}
}
SortUtils.quickSort(source_vec);
return source_vec;
}
public static boolean containSource(Vector sources, String source) {
if (sources == null || sources.size() == 0) return false;
for (int i=0; i<sources.size(); i++) {
String s = (String) sources.elementAt(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String src = (String) ret_vec.elementAt(2);
if (src.compareTo(source) == 0) return true;
}
return false;
}
public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
SortUtils.quickSort(v);
return v;
}
protected boolean isValidForSAB(AssociatedConcept ac, String sab) {
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue())
if ("Source".equalsIgnoreCase(qualifier.getContent())
&& sab.equalsIgnoreCase(qualifier.getName()))
return true;
return false;
}
public Vector sortSynonyms(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String key = term_name + term_source_code;
if (sortBy.compareTo("type") == 0) key = term_type + term_name;
if (sortBy.compareTo("source") == 0) key = term_source + term_name;
if (sortBy.compareTo("code") == 0) key = term_source_code + term_name;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) {
HashSet hset = new HashSet();
Vector v = new Vector();
Vector associated_concepts = getAssociatedConcepts(scheme, version, code, sab);
for (int i=0; i<associated_concepts.size(); i++) {
Concept c = (Concept) associated_concepts.elementAt(i);
Vector synonyms = getSynonyms(c, sab);
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
if (!hset.contains(s))
{
v.add(s);
hset.add(s);
}
}
}
SortUtils.quickSort(v);
return v;
}
}
|
package com.intellij.ide.projectView.impl;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.SelectableTreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.nodes.ClassTreeNode;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
public class ClassesTreeStructureProvider implements SelectableTreeStructureProvider {
private final Project myProject;
public ClassesTreeStructureProvider(Project project) {
myProject = project;
}
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
for (final AbstractTreeNode child : children) {
Object o = child.getValue();
if (o instanceof PsiClassOwner) {
final ViewSettings settings1 = ((ProjectViewNode)parent).getSettings();
final PsiClassOwner classOwner = (PsiClassOwner)o;
PsiClass[] classes = classOwner.getClasses();
if (classes.length == 1 && !(classes[0] instanceof SyntheticElement)) {
result.add(new ClassTreeNode(myProject, classes[0], settings1));
} else {
result.add(new PsiClassOwnerTreeNode(classOwner, settings1));
}
continue;
}
result.add(child);
}
return result;
}
public Object getData(Collection<AbstractTreeNode> selected, String dataName) {
return null;
}
public PsiElement getTopLevelElement(final PsiElement element) {
PsiFile baseRootFile = getBaseRootFile(element);
if (baseRootFile == null) return null;
PsiElement current = element;
while (current != null) {
if (current instanceof PsiFileSystemItem) {
break;
}
if (isTopLevelClass(current, baseRootFile)) {
break;
}
current = current.getParent();
}
if (current instanceof PsiClassOwner) {
PsiClass[] classes = ((PsiClassOwner)current).getClasses();
if (classes.length > 0 && isTopLevelClass(classes[0], baseRootFile)) {
current = classes[0];
}
}
return current instanceof PsiClass ? current : baseRootFile;
}
@Nullable
private static PsiFile getBaseRootFile(PsiElement element) {
final PsiFile containingFile = element.getContainingFile();
if (containingFile == null) return null;
final FileViewProvider viewProvider = containingFile.getViewProvider();
return viewProvider.getPsi(viewProvider.getBaseLanguage());
}
private static boolean isTopLevelClass(final PsiElement element, PsiFile baseRootFile) {
if (!(element instanceof PsiClass)) {
return false;
}
final PsiElement parent = element.getParent();
// do not select JspClass
return parent instanceof PsiFile && parent.getLanguage() == baseRootFile.getLanguage();
}
private static class PsiClassOwnerTreeNode extends PsiFileNode {
public PsiClassOwnerTreeNode(PsiClassOwner classOwner, ViewSettings settings) {
super(classOwner.getProject(), classOwner, settings);
}
@Override
public Collection<AbstractTreeNode> getChildrenImpl() {
final ViewSettings settings = getSettings();
final ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
for (PsiClass aClass : ((PsiClassOwner)getValue()).getClasses()) {
if (!(aClass instanceof SyntheticElement)) {
result.add(new ClassTreeNode(myProject, aClass, settings));
}
}
return result;
}
protected void updateImpl(PresentationData data) {
super.updateImpl(data);
data.setPresentableText(getValue().getName());
data.setIcons(getValue().getViewProvider().getVirtualFile().getIcon());
}
}
}
|
package de.halfreal.spezi.mvc.internal;
import static javax.tools.Diagnostic.Kind.*;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import de.halfreal.spezi.mvc.Model;
@SupportedAnnotationTypes("de.halfreal.spezi.mvc.Model")
public class ModelProcessor extends AbstractProcessor {
private static final String HEADER = "/* Generated code. Do not modify! */\n";
private static final String MODEL_BASE_CLASS = "de.halfreal.spezi.mvc.AbstractModel";
private Filer filer;
private Types typeUtils;
private void addTypes(Set<String> imports, TypeMirror type) {
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
Element declaredElement = declaredType.asElement();
imports.add(declaredElement.toString());
for (TypeMirror typeArgument : declaredType.getTypeArguments()) {
addTypes(imports, typeArgument);
}
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
if (wildcardType.getExtendsBound() != null) {
addTypes(imports, wildcardType.getExtendsBound());
}
if (wildcardType.getSuperBound() != null) {
addTypes(imports, wildcardType.getSuperBound());
}
} else if (type instanceof ArrayType) {
ArrayType arrayType = (ArrayType) type;
addTypes(imports, arrayType.getComponentType());
}
}
private void appendClassFooter(StringBuilder builder) {
builder.append("}\n");
}
private void appendClassHeader(StringBuilder builder,
TypeElement typeElement) {
String className = getClassName(typeElement);
String parameterAppend = getClassTypeParameter(typeElement, true);
String parameterAppendWithoutBounds = getClassTypeParameter(
typeElement, false);
builder.append("public class ").append(className)
.append(parameterAppend).append(" extends ")
.append(typeElement.getSimpleName())
.append(parameterAppendWithoutBounds).append(" {\n\n");
}
private void appendGettersAndSetters(StringBuilder builder,
TypeElement typeElement) {
for (Element enclosedElement : typeElement.getEnclosedElements()) {
if (enclosedElement instanceof VariableElement) {
VariableElement variableElement = (VariableElement) enclosedElement;
if (isConstant(variableElement)) {
continue;
}
if (!hasValidModifiers(variableElement)) {
error(variableElement,
"Variable must have either constant modifiers (public static final) or no modifiers (%s.%s)",
typeElement, variableElement);
}
appendVariable(builder, enclosedElement,
variableElement.asType());
}
}
}
private void appendHeader(StringBuilder builder) {
builder.append(HEADER);
}
private void appendImports(StringBuilder builder, TypeElement typeElement) {
Set<String> imports = new TreeSet<String>();
imports.add("de.halfreal.spezi.mvc.Key");
for (Element enclosedElement : typeElement.getEnclosedElements()) {
if (enclosedElement instanceof VariableElement) {
VariableElement variableElement = (VariableElement) enclosedElement;
addTypes(imports, variableElement.asType());
}
}
for (TypeParameterElement parameters : typeElement.getTypeParameters()) {
for (TypeMirror bound : parameters.getBounds()) {
addTypes(imports, bound);
}
}
for (String importClass : imports) {
builder.append("import ").append(importClass).append(";\n");
}
builder.append("\n");
}
private void appendKeysClass(StringBuilder builder, TypeElement typeElement) {
builder.append("\tpublic static class Keys {\n\n");
for (Element enclosedElement : typeElement.getEnclosedElements()) {
if (enclosedElement instanceof VariableElement) {
VariableElement variableElement = (VariableElement) enclosedElement;
if (isConstant(variableElement)) {
continue;
}
TypeMirror type = variableElement.asType();
if (type instanceof TypeVariable) {
builder.append("\t\tpublic static final Key<Object>")
.append(" ")
.append(getConstantName(enclosedElement
.getSimpleName()))
.append(" = new Key<Object>").append("(\"")
.append(variableElement.getSimpleName())
.append("\");\n");
} else {
builder.append("\t\tpublic static final Key<")
.append(getTypeString(type, true, true))
.append("> ")
.append(getConstantName(enclosedElement
.getSimpleName())).append(" = new Key<")
.append(getTypeString(type, true, true))
.append(">(\"")
.append(variableElement.getSimpleName())
.append("\");\n");
}
}
}
builder.append("\n\t}\n\n");
}
private void appendPackage(StringBuilder builder, TypeElement typeElement) {
PackageElement packageElement = (PackageElement) typeElement
.getEnclosingElement();
builder.append("package ").append(packageElement.getQualifiedName())
.append(";\n\n");
}
private void appendVariable(StringBuilder builder, Element enclosedElement,
TypeMirror declaredType) {
builder.append("\tpublic ")
.append(getTypeString(declaredType, false, false)).append(" ")
.append(getGetterName(enclosedElement.getSimpleName()))
.append("() {\n");
builder.append("\t\treturn ").append(enclosedElement.getSimpleName())
.append(";\n");
builder.append("\t}\n\n");
builder.append("\tpublic void ")
.append(getSetterName(enclosedElement.getSimpleName()))
.append("(").append(getTypeString(declaredType, false, false))
.append(" ").append(enclosedElement.getSimpleName())
.append(") {\n");
builder.append("\t\t")
.append(getTypeString(declaredType, false, false))
.append(" oldValue = this.")
.append(enclosedElement.getSimpleName()).append(";\n");
builder.append("\t\tthis.").append(enclosedElement.getSimpleName())
.append(" = ").append(enclosedElement.getSimpleName())
.append(";\n");
builder.append("\t\tfireChange(").append("Keys.")
.append(getConstantName(enclosedElement.getSimpleName()))
.append(", oldValue, ").append(enclosedElement.getSimpleName())
.append(");\n");
builder.append("\t}\n\n");
}
private String createArrayTypeString(TypeMirror type, int dimension,
boolean convertPrimitives, boolean staticTyping) {
if (type instanceof ArrayType) {
TypeMirror componentType = ((ArrayType) type).getComponentType();
return createArrayTypeString(componentType, dimension + 1,
convertPrimitives, staticTyping);
} else {
StringBuilder sb = new StringBuilder();
sb.append(getTypeString(type, convertPrimitives, staticTyping));
for (int i = 0; i < dimension; i++) {
sb.append("[]");
}
return sb.toString();
}
}
private String createModelBody(TypeElement typeElement, TypeMirror type) {
StringBuilder builder = new StringBuilder();
appendHeader(builder);
appendPackage(builder, typeElement);
appendImports(builder, typeElement);
appendClassHeader(builder, typeElement);
appendKeysClass(builder, typeElement);
appendGettersAndSetters(builder, typeElement);
appendClassFooter(builder);
return builder.toString();
}
private void createModelClass(TypeElement typeElement) {
TypeMirror type = typeElement.asType();
Element element = typeElement.getEnclosingElement();
if (element instanceof PackageElement) {
PackageElement packageElement = (PackageElement) element;
String fileName = getPackageName(packageElement) + "."
+ getClassName(typeElement);
try {
String modelBody = createModelBody(typeElement, type);
writeModelClass(fileName, modelBody, typeElement);
} catch (RuntimeException re) {
error(element, re.getMessage());
}
} else {
// TODO add support for inner classes
error(element, "Cannot generate Model for inner Classes. %s",
element.toString());
}
}
private void error(Element element, String message, Object... args) {
processingEnv.getMessager().printMessage(ERROR,
String.format(message, args), element);
}
private void error(TypeElement typeElement, Exception e) {
processingEnv.getMessager().printMessage(ERROR,
e.getClass().getName() + ": " + e.getMessage());
}
private String getClassName(TypeElement typeElement) {
if (typeElement.getSimpleName().toString().endsWith("Stub")) {
return typeElement.getSimpleName().toString()
.substring(0, typeElement.getSimpleName().length() - 4);
} else {
return typeElement.getSimpleName() + "Model";
}
}
public String getClassTypeParameter(TypeElement typeElement,
boolean withBounds) {
String parameterAppend = "";
List<? extends TypeParameterElement> typeParameters = typeElement
.getTypeParameters();
if (typeParameters != null && !typeParameters.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("<");
for (TypeParameterElement param : typeParameters) {
sb.append(param.getSimpleName());
if (withBounds && param.getBounds() != null
&& !param.getBounds().isEmpty()) {
sb.append(" extends ").append(
getTypeString(param.getBounds().get(0), false,
false));
}
sb.append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(">");
parameterAppend = sb.toString();
}
return parameterAppend;
}
private String getConstantName(Name simpleName) {
String regex = "([a-z])([A-Z])";
String replacement = "$1_$2";
return simpleName.toString().replaceAll(regex, replacement)
.toUpperCase();
}
private String getGetterName(Name simpleName) {
return "get" + getUppercaseName(simpleName);
}
private String getPackageName(PackageElement packageElement) {
return packageElement.getQualifiedName().toString();
}
private String getSetterName(Name simpleName) {
return "set" + getUppercaseName(simpleName);
}
private String getTypeName(Element declaredElement) {
String[] names = declaredElement.toString().split("\\.");
return names[names.length - 1];
}
private String getTypeString(TypeMirror type, boolean convertPrimitives,
boolean staticTyping) {
StringBuilder typeBuilder = new StringBuilder();
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
Element declaredElement = declaredType.asElement();
typeBuilder.append(getTypeName(declaredElement));
List<? extends TypeMirror> typeArguments = declaredType
.getTypeArguments();
if (typeArguments.size() > 0) {
typeBuilder.append("<");
boolean first = true;
for (TypeMirror typeArgument : typeArguments) {
if (first) {
first = false;
} else {
typeBuilder.append(",");
}
typeBuilder.append(getTypeString(typeArgument,
convertPrimitives, staticTyping));
}
typeBuilder.append(">");
}
return typeBuilder.toString();
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
if (wildcardType.getExtendsBound() == null
&& wildcardType.getSuperBound() == null) {
return "?";
} else if (wildcardType.getExtendsBound() != null) {
// ? extends Number
return String.format(
"? extends %s",
getTypeString(wildcardType.getExtendsBound(),
convertPrimitives, staticTyping));
} else {
// ? super T
return String.format(
"? super %s",
getTypeString(wildcardType.getSuperBound(),
convertPrimitives, staticTyping));
}
} else if (type instanceof PrimitiveType) {
PrimitiveType primitiveType = (PrimitiveType) type;
if (convertPrimitives) {
try {
TypeElement boxedClass = typeUtils
.boxedClass(primitiveType);
return getTypeString(boxedClass.asType(),
convertPrimitives, staticTyping);
} catch (NullPointerException ex) {
return primitiveType.toString();
}
} else {
return primitiveType.toString();
}
} else if (type instanceof ArrayType) {
return createArrayTypeString(type, 0, convertPrimitives,
staticTyping);
} else if (type instanceof TypeVariable) {
if (staticTyping) {
return "?";
} else {
return type.toString();
}
} else {
throw new RuntimeException("Cannot convert " + type
+ " to String representation!");
}
}
private String getUppercaseName(Name simpleName) {
return simpleName.toString().substring(0, 1).toUpperCase()
+ simpleName.toString().substring(1);
}
private boolean hasValidModifiers(VariableElement variableElement) {
Set<Modifier> modifiers = variableElement.getModifiers();
if (modifiers.size() != 0) {
return false;
}
return true;
}
@Override
public synchronized void init(ProcessingEnvironment env) {
super.init(env);
filer = env.getFiler();
typeUtils = env.getTypeUtils();
}
private boolean isConstant(VariableElement variableElement) {
Set<Modifier> modifiers = variableElement.getModifiers();
if (modifiers.size() != 3) {
return false;
}
return modifiers.contains(Modifier.PUBLIC)
&& modifiers.contains(Modifier.STATIC)
&& modifiers.contains(Modifier.FINAL);
}
private boolean isSubtypeOfAbstractModel(Element element) {
if (!(element instanceof TypeElement)) {
return false;
}
TypeElement typeElement = (TypeElement) element;
return isSubtypeOfAbstractModel(typeElement.getSuperclass());
}
private boolean isSubtypeOfAbstractModel(TypeMirror typeMirror) {
if (!(typeMirror instanceof DeclaredType)) {
return false;
}
DeclaredType declaredType = (DeclaredType) typeMirror;
if (declaredType.toString().equals(MODEL_BASE_CLASS)) {
return true;
} else {
return isSubtypeOfAbstractModel(declaredType.asElement());
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends Element> modelElements = roundEnv
.getElementsAnnotatedWith(Model.class);
for (Element element : modelElements) {
if (element instanceof TypeElement) {
processElement((TypeElement) element);
}
}
return true;
}
private void processElement(TypeElement element) {
if (isSubtypeOfAbstractModel(element)) {
createModelClass(element);
} else {
error(element,
"Model stub class must extend de.halfreal.spezi.mvc.AbstractModel (%s).",
element);
}
}
private void writeModelClass(String fileName, String modelBody,
TypeElement typeElement) {
try {
JavaFileObject jfo = filer.createSourceFile(fileName);
Writer writer = jfo.openWriter();
writer.write(modelBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
error(typeElement, e);
}
}
}
|
package org.vaadin.spring.http;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class HttpResponseFilter implements Filter {
private ThreadLocal<HttpServletResponse> responses = new ThreadLocal<HttpServletResponse>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletResponse r = (HttpServletResponse) response;
responses.set(r);
chain.doFilter(request, response);
} finally {
responses.remove();
}
}
public HttpServletResponse getHttpServletReponse() {
return responses.get();
}
@Override
public void destroy() {
}
}
|
package org.objectweb.proactive.extra.ressourcemanager;
import java.io.CharArrayWriter;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class SimpleSchema {
private SAXParserFactory factory; // Creates parser object
private SAXParser parser; // Holds a parser object
private XMLReader xmlReader; // Object that parses the file
private DefaultHandler handler; // Defines the handler for this parser
private boolean valid = true;
// Set schema constants
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http:
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public SimpleSchema() throws SAXException {
try {
factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
if (factory.isValidating()) {
System.out.println("The parser is validating");
}
//Create Parser
parser = factory.newSAXParser();
// Enable Schemas
parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
// true);
//Create XMLReader
xmlReader = parser.getXMLReader();
ContentHandler cHandler = new MyDefaultHandler();
ErrorHandler eHandler = new MyDefaultHandler();
xmlReader.setContentHandler(cHandler);
xmlReader.setErrorHandler(eHandler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public void parseDocument(String xmlFile) {
try {
xmlReader.parse(xmlFile);
if (valid) {
System.out.println("Document is valid!");
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
if (args.length != 1) {
System.out.println("Usage: java SimpleSchema " +
"[XML Document Filename]");
System.exit(0);
}
SimpleSchema xmlApp = new SimpleSchema();
xmlApp.parseDocument(args[0]);
} catch (SAXException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class MyDefaultHandler extends DefaultHandler {
private CharArrayWriter buff = new CharArrayWriter();
private String errMessage = "";
/* With a handler class, just override the methods you need to use
*/
// Start Error Handler code here
public void warning(SAXParseException e) {
System.out.println("Warning Line " + e.getLineNumber() + ": " +
e.getMessage() + "\n");
}
public void error(SAXParseException e) {
errMessage = new String("Error Line " + e.getLineNumber() + ": " +
e.getMessage() + "\n");
System.out.println(errMessage);
valid = false;
}
public void fatalError(SAXParseException e) {
errMessage = new String("Error Line " + e.getLineNumber() + ": " +
e.getMessage() + "\n");
System.out.println(errMessage);
valid = false;
}
}
}
|
import java.util.*;
/**
* Loop through the tiles and find out how many of them have matching edges. Then,
* based upon the number of shared edges we do the following:
*
* 0: ERROR!!
* 1: If a tile has only one matching edge, then it's easy to say where it needs
* to be placed.
* 2: Work outwards from the centre.
*/
public class Solver
{
public Solver (boolean debug)
{
_debug = debug;
}
/*
* This time we need to solve the image and return the entire
* thing assembled, i.e., not just the corners.
*/
public Vector<Tile> solve (Vector<Tile> tiles)
{
HashMap<Long, Integer> tileTable = new HashMap<Long, Integer>();
for (int i = 0; i < tiles.size(); i++)
tileTable.put(tiles.elementAt(i).getID(), i);
System.out.println("**GOT "+tileTable);
HashSet<Tile> visited = new HashSet<Tile>();
LinkedList<Tile> queue = new LinkedList<Tile>();
queue.add(tiles.get(0));
while (!queue.isEmpty())
{
Tile current = queue.poll();
visited.add(current);
for (int j = 0; j < tiles.size(); j++)
{
Tile t = tiles.elementAt(j);
if (!visited.contains(t) && !current.equals(t))
{
if (connects(current, t))
queue.add(t);
}
}
}
System.out.println("**NOW have "+visited);
for (int i = 0; i < tiles.size(); i++)
{
Tile t = tiles.elementAt(i);
for (int j = 0; j < tiles.size(); j++)
{
if (!t.equals(tiles.elementAt(j)))
{
connects(t, tiles.elementAt(j));
}
}
}
System.out.println("**NOW GOT\n"+tiles);
Image theImage = createImage(tiles, tileTable);
System.out.println("**HAVE\n"+theImage);
return null;
}
private boolean connects (Tile theTile, Tile toCheck)
{
if (_debug)
System.out.println("Checking "+toCheck.getID()+" against "+theTile.getID());
for (int i = 0; i < 4; i++)
{
if (theTile.connectBottomToTop(toCheck) || theTile.connectTopToBottom(toCheck) ||
theTile.connectLeftToRight(toCheck) || theTile.connectRightToLeft(toCheck))
{
return true;
}
if (!toCheck.isFrozen())
toCheck.rotate();
}
if (!toCheck.isFrozen())
toCheck.invert();
for (int i = 0; i < 4; i++)
{
if (theTile.connectBottomToTop(toCheck) || theTile.connectTopToBottom(toCheck) ||
theTile.connectLeftToRight(toCheck) || theTile.connectRightToLeft(toCheck))
{
return true;
}
if (!toCheck.isFrozen())
toCheck.rotate();
}
return false;
}
private Image createImage (Vector<Tile> tiles, HashMap<Long, Integer> tileTable)
{
Tile topLeftCorner = null;
Image theImage = new Image((int) Math.sqrt(tiles.size()), (int) Math.sqrt(tiles.size()), _debug);
for (int i = 0; (i < tiles.size()) && (topLeftCorner == null); i++)
{
Tile t = tiles.elementAt(i);
if (t.getNumberOfConnections() == 2) // has to be a corner!
{
if ((t.getConnections()[Tile.TOP] == 0) && (t.getConnections()[Tile.LEFT] == 0))
topLeftCorner = t;
}
}
Tile current = topLeftCorner;
int x = 0;
int y = 0;
while (current.getConnections()[Tile.BOTTOM] != 0)
{
Tile left = current;
while (current.getConnections()[Tile.RIGHT] != 0)
{
System.out.println("adding "+current.getID()+" to "+y+" "+x);
theImage.addTile(x, y, current);
x++;
current = tiles.get(tileTable.get(current.getConnections()[Tile.RIGHT]));
if (current.getConnections()[Tile.RIGHT] == 0)
{
System.out.println("adding "+current.getID()+" to "+y+" "+x);
theImage.addTile(x, y, current);
x = 0;
y++;
}
}
current = tiles.get(tileTable.get(left.getConnections()[Tile.BOTTOM]));
if (current.getConnections()[Tile.BOTTOM] == 0)
{
while (current.getConnections()[Tile.RIGHT] != 0)
{
System.out.println("adding "+current.getID()+" to "+y+" "+x);
theImage.addTile(x, y, current);
x++;
current = tiles.get(tileTable.get(current.getConnections()[Tile.RIGHT]));
if (current.getConnections()[Tile.RIGHT] == 0)
{
System.out.println("adding "+current.getID()+" to "+y+" "+x);
theImage.addTile(x, y, current);
y++;
}
}
}
}
return theImage;
}
private boolean _debug;
}
|
package cgeo.geocaching.maps;
import butterknife.ButterKnife;
import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.Waypoint;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.gc.GCLogin;
import cgeo.geocaching.connector.gc.MapTokens;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Viewport;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapActivityImpl;
import cgeo.geocaching.maps.interfaces.MapControllerImpl;
import cgeo.geocaching.maps.interfaces.MapItemFactory;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.sensors.DirectionProvider;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.IGeoData;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.LiveMapInfoDialogBuilder;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.LeastRecentlyUsedSet;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.Subscriptions;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Class representing the Map in c:geo
*/
public class CGeoMap extends AbstractMap implements ViewFactory {
/** max. number of caches displayed in the Live Map */
public static final int MAX_CACHES = 500;
/**
* initialization with an empty subscription to make static code analysis tools more happy
*/
private Subscription resumeSubscription = Subscriptions.empty();
/** Controls the behavior of the map */
public enum MapMode {
/** Live Map */
LIVE,
/** Map around some coordinates */
COORDS,
/** Map with a single cache (no reload on move) */
SINGLE,
/** Map with a list of caches (no reload on move) */
LIST
}
/** Handler Messages */
private static final int HIDE_PROGRESS = 0;
private static final int SHOW_PROGRESS = 1;
private static final int UPDATE_TITLE = 0;
private static final int INVALIDATE_MAP = 1;
private static final int UPDATE_PROGRESS = 0;
private static final int FINISHED_LOADING_DETAILS = 1;
//Menu
private static final String EXTRAS_GEOCODE = "geocode";
private static final String EXTRAS_COORDS = "coords";
private static final String EXTRAS_WPTTYPE = "wpttype";
private static final String EXTRAS_MAPSTATE = "mapstate";
private static final String EXTRAS_SEARCH = "search";
private static final String EXTRAS_MAP_TITLE = "mapTitle";
private static final String EXTRAS_MAP_MODE = "mapMode";
private static final String EXTRAS_LIVE_ENABLED = "liveEnabled";
private static final String BUNDLE_MAP_SOURCE = "mapSource";
private static final String BUNDLE_MAP_STATE = "mapState";
private static final String BUNDLE_LIVE_ENABLED = "liveEnabled";
private static final String BUNDLE_TRAIL_HISTORY = "trailHistory";
// Those are initialized in onCreate() and will never be null afterwards
private Resources res;
private Activity activity;
private CgeoApplication app;
private MapItemFactory mapItemFactory;
private String mapTitle;
private LeastRecentlyUsedSet<Geocache> caches;
private MapViewImpl mapView;
private CachesOverlay overlayCaches;
private PositionAndScaleOverlay overlayPositionAndScale;
final private GeoDirHandler geoDirUpdate;
private SearchResult searchIntent = null;
private String geocodeIntent = null;
private Geopoint coordsIntent = null;
private WaypointType waypointTypeIntent = null;
private int[] mapStateIntent = null;
// status data
/** Last search result used for displaying header */
private SearchResult lastSearchResult = null;
private MapTokens tokens = null;
private boolean noMapTokenShowed = false;
// map status data
private boolean followMyLocation = false;
// threads
private Subscription loadTimer;
private LoadDetails loadDetailsThread = null;
/** Time of last {@link LoadRunnable} run */
private volatile long loadThreadRun = 0L;
//Interthread communication flag
private volatile boolean downloaded = false;
/** Count of caches currently visible */
private int cachesCnt = 0;
/** List of waypoints in the viewport */
private final LeastRecentlyUsedSet<Waypoint> waypoints = new LeastRecentlyUsedSet<>(MAX_CACHES);
// storing for offline
private ProgressDialog waitDialog = null;
private int detailTotal = 0;
private int detailProgress = 0;
private long detailProgressTime = 0L;
// views
private CheckBox myLocSwitch = null;
/** Controls the map behavior */
private MapMode mapMode = null;
/** Live mode enabled for map. **/
private boolean isLiveEnabled;
// other things
private boolean markersInvalidated = false; // previous state for loadTimer
private boolean centered = false; // if map is already centered
private boolean alreadyCentered = false; // -""- for setting my location
private static final Set<String> dirtyCaches = new HashSet<>();
/**
* if live map is enabled, this is the minimum zoom level, independent of the stored setting
*/
private static final int MIN_LIVEMAP_ZOOM = 12;
// Thread pooling
private static BlockingQueue<Runnable> displayQueue = new ArrayBlockingQueue<>(1);
private static ThreadPoolExecutor displayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, displayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<>(1);
private static ThreadPoolExecutor downloadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, downloadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> loadQueue = new ArrayBlockingQueue<>(1);
private static ThreadPoolExecutor loadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, loadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
// handlers
/** Updates the titles */
private final static class DisplayHandler extends Handler {
private final WeakReference<CGeoMap> mapRef;
public DisplayHandler(@NonNull final CGeoMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
final CGeoMap map = mapRef.get();
if (map == null) {
return;
}
switch (what) {
case UPDATE_TITLE:
// set title
final StringBuilder title = new StringBuilder();
if (map.mapMode == MapMode.LIVE && map.isLiveEnabled) {
title.append(map.res.getString(R.string.map_live));
} else {
title.append(map.mapTitle);
}
map.countVisibleCaches();
if (!map.caches.isEmpty() && !map.mapTitle.contains("[")) {
title.append(" [").append(map.cachesCnt);
if (map.cachesCnt != map.caches.size()) {
title.append('/').append(map.caches.size());
}
title.append(']');
}
if (Settings.isDebug() && map.lastSearchResult != null && StringUtils.isNotBlank(map.lastSearchResult.getUrl())) {
title.append('[').append(map.lastSearchResult.getUrl()).append(']');
}
map.setTitle(title.toString());
break;
case INVALIDATE_MAP:
map.mapView.repaintRequired(null);
break;
default:
break;
}
}
}
final private Handler displayHandler = new DisplayHandler(this);
private void setTitle(final String title) {
/* Compatibility for the old Action Bar, only used by the maps activity at the moment */
final TextView titleview = ButterKnife.findById(activity, R.id.actionbar_title);
if (titleview != null) {
titleview.setText(title);
}
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) {
setTitleHoneyComb(title);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setTitleHoneyComb(final String title) {
activity.getActionBar().setTitle(title);
}
/** Updates the progress. */
private static final class ShowProgressHandler extends Handler {
private int counter = 0;
@NonNull private final WeakReference<CGeoMap> mapRef;
public ShowProgressHandler(@NonNull final CGeoMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
showProgress(false);
}
} else if (what == SHOW_PROGRESS) {
showProgress(true);
counter++;
}
}
private void showProgress(final boolean show) {
final CGeoMap map = mapRef.get();
if (map == null) {
return;
}
final ProgressBar progress = (ProgressBar) map.activity.findViewById(R.id.actionbar_progress);
if (progress != null) {
if (show) {
progress.setVisibility(View.VISIBLE);
} else {
progress.setVisibility(View.GONE);
}
}
if (Build.VERSION.SDK_INT >= 11) {
map.activity.setProgressBarIndeterminateVisibility(show);
}
}
}
final private Handler showProgressHandler = new ShowProgressHandler(this);
final private class LoadDetailsHandler extends CancellableHandler {
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_PROGRESS) {
if (waitDialog != null) {
final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
final int minsRemaining = secondsRemaining / 60;
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog.setOnCancelListener(null);
}
}
}
@Override
public void handleCancel(final Object extra) {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
}
}
/* Current source id */
private int currentSourceId;
public CGeoMap(final MapActivityImpl activity) {
super(activity);
geoDirUpdate = new UpdateLoc(this);
}
protected void countVisibleCaches() {
cachesCnt = mapView.getViewport().count(caches.getAsList());
}
@Override
public void onSaveInstanceState(final Bundle outState) {
outState.putInt(BUNDLE_MAP_SOURCE, currentSourceId);
outState.putIntArray(BUNDLE_MAP_STATE, currentMapState());
outState.putBoolean(BUNDLE_LIVE_ENABLED, isLiveEnabled);
outState.putParcelableArrayList(BUNDLE_TRAIL_HISTORY, overlayPositionAndScale.getHistory());
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// class init
res = this.getResources();
activity = this.getActivity();
app = (CgeoApplication) activity.getApplication();
final int countBubbleCnt = DataStore.getAllCachesCount();
caches = new LeastRecentlyUsedSet<>(MAX_CACHES + countBubbleCnt);
final MapProvider mapProvider = Settings.getMapProvider();
mapItemFactory = mapProvider.getMapItemFactory();
// Get parameters from the intent
final Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
mapMode = (MapMode) extras.get(EXTRAS_MAP_MODE);
isLiveEnabled = extras.getBoolean(EXTRAS_LIVE_ENABLED, false);
searchIntent = extras.getParcelable(EXTRAS_SEARCH);
geocodeIntent = extras.getString(EXTRAS_GEOCODE);
coordsIntent = extras.getParcelable(EXTRAS_COORDS);
waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE));
mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE);
mapTitle = extras.getString(EXTRAS_MAP_TITLE);
}
else {
mapMode = MapMode.LIVE;
isLiveEnabled = Settings.isLiveMap();
}
if (StringUtils.isBlank(mapTitle)) {
mapTitle = res.getString(R.string.map_map);
}
ArrayList<Location> trailHistory = null;
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource().getNumericalId());
mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE);
isLiveEnabled = savedInstanceState.getBoolean(BUNDLE_LIVE_ENABLED, false);
trailHistory = savedInstanceState.getParcelableArrayList(BUNDLE_TRAIL_HISTORY);
} else {
currentSourceId = Settings.getMapSource().getNumericalId();
}
// If recreating from an obsolete map source, we may need a restart
if (changeMapSource(Settings.getMapSource())) {
return;
}
// reset status
noMapTokenShowed = false;
ActivityMixin.keepScreenOn(activity, true);
// set layout
ActivityMixin.setTheme(activity);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
}
activity.setContentView(mapProvider.getMapLayoutId());
setTitle(res.getString(R.string.map_map));
// initialize map
mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId());
mapView.setMapSource();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.preLoad();
mapView.setOnDragListener(new MapDragListener(this));
// initialize overlays
mapView.clearOverlays();
overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker));
overlayPositionAndScale = mapView.createAddPositionAndScaleOverlay();
if (trailHistory != null) {
overlayPositionAndScale.setHistory(trailHistory);
}
mapView.repaintRequired(null);
setZoom(Settings.getMapZoom());
mapView.getMapController().setCenter(Settings.getMapCenter());
if (null == mapStateIntent) {
followMyLocation = mapMode == MapMode.LIVE;
} else {
followMyLocation = 1 == mapStateIntent[3];
if ((overlayCaches.getCircles() ? 1 : 0) != mapStateIntent[4]) {
overlayCaches.switchCircles();
}
}
if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) {
centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent);
}
final CheckBox locSwitch = ButterKnife.findById(activity, R.id.my_position);
if (locSwitch!=null) {
initMyLocationSwitchButton(locSwitch);
}
prepareFilterBar();
if (!app.isLiveMapHintShownInThisSession() && !Settings.getHideLiveMapHint() && Settings.getLiveMapHintShowCount() <= 3) {
LiveMapInfoDialogBuilder.create(activity).show();
}
}
private void initMyLocationSwitchButton(final CheckBox locSwitch) {
myLocSwitch = locSwitch;
/* TODO: Switch back to ImageSwitcher for animations?
myLocSwitch.setFactory(this);
myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); */
myLocSwitch.setOnClickListener(new MyLocationListener(this));
switchMyLocationButton();
}
/**
* Set the zoom of the map. The zoom is restricted to a certain minimum in case of live map.
*
* @param zoom
*/
private void setZoom(final int zoom) {
mapView.getMapController().setZoom(isLiveEnabled ? Math.max(zoom, MIN_LIVEMAP_ZOOM) : zoom);
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
final String cacheType = Settings.getCacheType().getL10n();
final TextView filterTitleView = ButterKnife.findById(activity, R.id.filter_text);
filterTitleView.setText(cacheType);
activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
activity.findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
@Override
public void onResume() {
super.onResume();
resumeSubscription = Subscriptions.from(geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR), startTimer());
if (!CollectionUtils.isEmpty(dirtyCaches)) {
for (final String geocode : dirtyCaches) {
final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
if (cache != null) {
// new collection type needs to remove first
caches.remove(cache);
// re-add to update the freshness
caches.add(cache);
}
}
dirtyCaches.clear();
// Update display
displayExecutor.execute(new DisplayRunnable(this));
}
}
@Override
public void onPause() {
resumeSubscription.unsubscribe();
savePrefs();
mapView.destroyDrawingCache();
MapUtils.clearCachedItems();
super.onPause();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// menu inflation happens in Google/Mapsforge specific classes
super.onCreateOptionsMenu(menu);
MapProviderFactory.addMapviewMenuItems(menu);
final SubMenu subMenuStrategy = menu.findItem(R.id.submenu_strategy).getSubMenu();
subMenuStrategy.setHeaderTitle(res.getString(R.string.map_strategy_title));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
/* if we have an Actionbar find the my position toggle */
final MenuItem item = menu.findItem(R.id.menu_toggle_mypos);
myLocSwitch = new CheckBox(activity);
myLocSwitch.setButtonDrawable(R.drawable.ic_menu_myposition);
item.setActionView(myLocSwitch);
initMyLocationSwitchButton(myLocSwitch);
} else {
// Already on the fake Actionbar
menu.removeItem(R.id.menu_toggle_mypos);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
super.onPrepareOptionsMenu(menu);
for (final MapSource mapSource : MapProviderFactory.getMapSources()) {
final MenuItem menuItem = menu.findItem(mapSource.getNumericalId());
if (menuItem != null) {
menuItem.setVisible(mapSource.isAvailable());
}
}
try {
MenuItem item = menu.findItem(R.id.menu_trail_mode);
item.setChecked(Settings.isMapTrail());
item = menu.findItem(R.id.menu_map_live); // live map
if (isLiveEnabled) {
item.setTitle(res.getString(R.string.map_live_disable));
} else {
item.setTitle(res.getString(R.string.map_live_enable));
}
item = menu.findItem(R.id.menu_mycaches_mode); // own & found caches
item.setChecked(Settings.isExcludeMyCaches());
final Set<String> geocodesInViewport = getGeocodesForCachesInViewport();
menu.findItem(R.id.menu_store_caches).setVisible(!isLoading() && CollectionUtils.isNotEmpty(geocodesInViewport) && new SearchResult(geocodesInViewport).hasUnsavedCaches());
item = menu.findItem(R.id.menu_circle_mode); // show circles
item.setChecked(overlayCaches.getCircles());
item = menu.findItem(R.id.menu_theme_mode); // show theme selection
item.setVisible(mapView.hasMapThemes());
menu.findItem(R.id.menu_as_list).setVisible(!isLoading());
menu.findItem(R.id.submenu_strategy).setVisible(isLiveEnabled);
switch (Settings.getLiveMapStrategy()) {
case FASTEST:
menu.findItem(R.id.menu_strategy_fastest).setChecked(true);
break;
case FAST:
menu.findItem(R.id.menu_strategy_fast).setChecked(true);
break;
case AUTO:
menu.findItem(R.id.menu_strategy_auto).setChecked(true);
break;
default: // DETAILED
menu.findItem(R.id.menu_strategy_detailed).setChecked(true);
}
} catch (final RuntimeException e) {
Log.e("CGeoMap.onPrepareOptionsMenu", e);
}
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case android.R.id.home:
ActivityMixin.navigateUp(activity);
return true;
case R.id.menu_trail_mode:
Settings.setMapTrail(!Settings.isMapTrail());
mapView.repaintRequired(overlayPositionAndScale);
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_map_live:
isLiveEnabled = !isLiveEnabled;
if (mapMode == MapMode.LIVE) {
Settings.setLiveMap(isLiveEnabled);
}
markersInvalidated = true;
lastSearchResult = null;
searchIntent = null;
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_store_caches:
if (!isLoading()) {
final Set<String> geocodesInViewport = getGeocodesForCachesInViewport();
final List<String> geocodes = new ArrayList<>();
for (final String geocode : geocodesInViewport) {
if (!DataStore.isOffline(geocode, null)) {
geocodes.add(geocode);
}
}
detailTotal = geocodes.size();
detailProgress = 0;
if (detailTotal == 0) {
ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing));
return true;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(activity).promptForListSelection(R.string.list_title,
new Action1<Integer>() {
@Override
public void call(final Integer selectedListId) {
storeCaches(geocodes, selectedListId);
}
}, true, StoredList.TEMPORARY_LIST_ID);
} else {
storeCaches(geocodes, StoredList.STANDARD_LIST_ID);
}
}
return true;
case R.id.menu_circle_mode:
overlayCaches.switchCircles();
mapView.repaintRequired(overlayCaches);
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_mycaches_mode:
Settings.setExcludeMine(!Settings.isExcludeMyCaches());
markersInvalidated = true;
ActivityMixin.invalidateOptionsMenu(activity);
if (!Settings.isExcludeMyCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_theme_mode:
selectMapTheme();
return true;
case R.id.menu_as_list: {
CacheListActivity.startActivityMap(activity, new SearchResult(getGeocodesForCachesInViewport()));
return true;
}
case R.id.menu_strategy_fastest: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FASTEST);
return true;
}
case R.id.menu_strategy_fast: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FAST);
return true;
}
case R.id.menu_strategy_auto: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.AUTO);
return true;
}
case R.id.menu_strategy_detailed: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.DETAILED);
return true;
}
default:
final MapSource mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
private void selectMapTheme() {
final File[] themeFiles = Settings.getMapThemeFiles();
String currentTheme = StringUtils.EMPTY;
final String currentThemePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isNotEmpty(currentThemePath)) {
final File currentThemeFile = new File(currentThemePath);
currentTheme = currentThemeFile.getName();
}
final List<String> names = new ArrayList<>();
names.add(res.getString(R.string.map_theme_builtin));
int currentItem = 0;
for (final File file : themeFiles) {
if (currentTheme.equalsIgnoreCase(file.getName())) {
currentItem = names.size();
}
names.add(file.getName());
}
final int selectedItem = currentItem;
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.map_theme_select);
builder.setSingleChoiceItems(names.toArray(new String[names.size()]), selectedItem,
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int newItem) {
if (newItem != selectedItem) {
// Adjust index because of <default> selection
if (newItem > 0) {
Settings.setCustomRenderThemeFile(themeFiles[newItem - 1].getPath());
} else {
Settings.setCustomRenderThemeFile(StringUtils.EMPTY);
}
mapView.setMapTheme();
}
dialog.cancel();
}
});
builder.show();
}
/**
* @return a non-null Set of geocodes corresponding to the caches that are shown on screen.
*/
private Set<String> getGeocodesForCachesInViewport() {
final Set<String> geocodes = new HashSet<>();
final List<Geocache> cachesProtected = caches.getAsList();
final Viewport viewport = mapView.getViewport();
for (final Geocache cache : cachesProtected) {
if (viewport.contains(cache)) {
geocodes.add(cache.getGeocode());
}
}
return geocodes;
}
/**
* Restart the current activity if the map provider has changed, or change the map source if needed.
*
* @param newSource
* the new map source, which can be the same as the current one
* @return true if a restart is needed, false otherwise
*/
private boolean changeMapSource(@NonNull final MapSource newSource) {
final MapSource oldSource = MapProviderFactory.getMapSource(currentSourceId);
final boolean restartRequired = oldSource == null || !MapProviderFactory.isSameActivity(oldSource, newSource);
Settings.setMapSource(newSource);
currentSourceId = newSource.getNumericalId();
if (restartRequired) {
mapRestart();
} else if (mapView != null) { // changeMapSource can be called by onCreate()
mapView.setMapSource();
ActivityMixin.invalidateOptionsMenu(activity);
}
return restartRequired;
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
// close old mapview
activity.finish();
// prepare information to restart a similar view
final Intent mapIntent = new Intent(activity, Settings.getMapProvider().getMapClass());
mapIntent.putExtra(EXTRAS_SEARCH, searchIntent);
mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent);
if (coordsIntent != null) {
mapIntent.putExtra(EXTRAS_COORDS, coordsIntent);
}
mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null);
mapIntent.putExtra(EXTRAS_MAP_TITLE, mapTitle);
mapIntent.putExtra(EXTRAS_MAP_MODE, mapMode);
mapIntent.putExtra(EXTRAS_LIVE_ENABLED, isLiveEnabled);
final int[] mapState = currentMapState();
if (mapState != null) {
mapIntent.putExtra(EXTRAS_MAPSTATE, mapState);
}
// start the new map
activity.startActivity(mapIntent);
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private int[] currentMapState() {
final GeoPointImpl mapCenter = mapView.getMapViewCenter();
return new int[] {
mapCenter.getLatitudeE6(),
mapCenter.getLongitudeE6(),
mapView.getMapZoomLevel(),
followMyLocation ? 1 : 0,
overlayCaches.getCircles() ? 1 : 0
};
}
private void savePrefs() {
Settings.setMapZoom(mapView.getMapZoomLevel());
Settings.setMapCenter(mapView.getMapViewCenter());
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final IGeoData geo) {
if (followMyLocation && !geo.isPseudoLocation()) {
centerMap(geo.getCoords());
}
}
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
Location currentLocation = new Location("");
boolean locationValid = false;
float currentHeading;
private long timeLastPositionOverlayCalculation = 0;
/**
* weak reference to the outer class
*/
private final WeakReference<CGeoMap> mapRef;
public UpdateLoc(final CGeoMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void updateGeoDir(final IGeoData geo, final float dir) {
if (geo.isPseudoLocation()) {
locationValid = false;
} else {
locationValid = true;
currentLocation = geo.getLocation();
currentHeading = DirectionProvider.getDirectionNow(dir);
repaintPositionOverlay();
}
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final CGeoMap map = mapRef.get();
if (map != null) {
final boolean needsRepaintForDistance = needsRepaintForDistance();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistance) {
if (map.followMyLocation) {
map.centerMap(new Geopoint(currentLocation));
}
}
if (needsRepaintForDistance || needsRepaintForHeading) {
map.overlayPositionAndScale.setCoordinates(currentLocation);
map.overlayPositionAndScale.setHeading(currentHeading);
map.mapView.repaintRequired(map.overlayPositionAndScale);
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location.");
}
}
}
boolean needsRepaintForHeading() {
final CGeoMap map = mapRef.get();
if (map == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, map.overlayPositionAndScale.getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistance() {
if (!locationValid) {
return false;
}
final CGeoMap map = mapRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.overlayPositionAndScale.getCoordinates();
float dist = Float.MAX_VALUE;
if (lastLocation != null) {
dist = currentLocation.distanceTo(lastLocation);
}
final float[] mapDimension = new float[1];
if (map.mapView.getWidth() < map.mapView.getHeight()) {
final double span = map.mapView.getLongitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension);
} else {
final double span = map.mapView.getLatitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension);
}
return dist > (mapDimension[0] * MIN_LOCATION_DELTA);
}
}
/**
* Starts the {@link LoadTimer}.
*/
private Subscription startTimer() {
if (coordsIntent != null) {
// display just one point
displayPoint(coordsIntent);
loadTimer = Subscriptions.empty();
} else {
loadTimer = Schedulers.newThread().createWorker().schedulePeriodically(new LoadTimerAction(this), 0, 250, TimeUnit.MILLISECONDS);
}
return loadTimer;
}
private static final class LoadTimerAction implements Action0 {
@NonNull private final WeakReference<CGeoMap> mapRef;
private int previousZoom = -100;
private Viewport previousViewport;
public LoadTimerAction(@NonNull final CGeoMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void call() {
final CGeoMap map = mapRef.get();
if (map == null) {
return;
}
try {
// get current viewport
final Viewport viewportNow = map.mapView.getViewport();
// Since zoomNow is used only for local comparison purposes,
// it is ok to use the Google Maps compatible zoom level of OSM Maps
final int zoomNow = map.mapView.getMapZoomLevel();
// check if map moved or zoomed
//TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move
final boolean moved = map.markersInvalidated || (map.isLiveEnabled && !map.downloaded) || (previousViewport == null) || zoomNow != previousZoom ||
(mapMoved(previousViewport, viewportNow) && (map.cachesCnt <= 0 || CollectionUtils.isEmpty(map.caches) || !previousViewport.includes(viewportNow)));
// update title on any change
if (moved || !viewportNow.equals(previousViewport)) {
map.displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
previousZoom = zoomNow;
// save new values
if (moved) {
map.markersInvalidated = false;
final long currentTime = System.currentTimeMillis();
if (1000 < (currentTime - map.loadThreadRun)) {
previousViewport = viewportNow;
loadExecutor.execute(new LoadRunnable(map));
}
}
} catch (final Exception e) {
Log.w("CGeoMap.startLoadtimer.start", e);
}
}
}
/**
* get if map is loading something
*
* @return
*/
public boolean isLoading() {
return !loadTimer.isUnsubscribed() &&
(loadExecutor.getActiveCount() > 0 ||
downloadExecutor.getActiveCount() > 0 ||
displayExecutor.getActiveCount() > 0);
}
/**
* Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadRunnable}.
* started by {@link LoadTimer}
*/
private static class LoadRunnable extends DoRunnable {
public LoadRunnable(@NonNull final CGeoMap map) {
super(map);
}
@Override
public void runWithMap(final CGeoMap map) {
map.doLoadRun();
}
}
private void doLoadRun() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
loadThreadRun = System.currentTimeMillis();
SearchResult searchResult;
if (mapMode == MapMode.LIVE) {
searchResult = isLiveEnabled ? new SearchResult() : new SearchResult(DataStore.loadStoredInViewport(mapView.getViewport(), Settings.getCacheType()));
} else {
// map started from another activity
searchResult = searchIntent != null ? new SearchResult(searchIntent) : new SearchResult();
if (geocodeIntent != null) {
searchResult.addGeocode(geocodeIntent);
}
}
// live mode search result
if (isLiveEnabled) {
searchResult.addSearchResult(DataStore.loadCachedInViewport(mapView.getViewport(), Settings.getCacheType()));
}
downloaded = true;
final Set<Geocache> cachesFromSearchResult = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_WAYPOINTS);
// update the caches
// new collection type needs to remove first
caches.removeAll(cachesFromSearchResult);
caches.addAll(cachesFromSearchResult);
final boolean excludeMine = Settings.isExcludeMyCaches();
final boolean excludeDisabled = Settings.isExcludeDisabledCaches();
if (mapMode == MapMode.LIVE) {
CGeoMap.filter(caches);
}
countVisibleCaches();
if (cachesCnt < Settings.getWayPointsThreshold() || geocodeIntent != null) {
// we don't want to see any stale waypoints
waypoints.clear();
if (isLiveEnabled || mapMode == MapMode.LIVE
|| mapMode == MapMode.COORDS) {
//All visible waypoints
final CacheType type = Settings.getCacheType();
final Set<Waypoint> waypointsInViewport = DataStore.loadWaypoints(mapView.getViewport(), excludeMine, excludeDisabled, type);
waypoints.addAll(waypointsInViewport);
}
else {
//All waypoints from the viewed caches
for (final Geocache c : caches.getAsList()) {
waypoints.addAll(c.getWaypoints());
}
}
}
else {
// we don't want to see any stale waypoints when above threshold
waypoints.clear();
}
//render
displayExecutor.execute(new DisplayRunnable(this));
if (isLiveEnabled) {
downloadExecutor.execute(new DownloadRunnable(this));
}
lastSearchResult = searchResult;
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
/**
* Worker thread downloading caches from the internet.
* Started by {@link LoadRunnable}.
*/
private static class DownloadRunnable extends DoRunnable {
public DownloadRunnable(final CGeoMap map) {
super(map);
}
@Override
public void runWithMap(final CGeoMap map) {
map.doDownloadRun();
}
}
private void doDownloadRun() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); // show progress
if (Settings.isGCConnectorActive()) {
if (tokens == null) {
tokens = GCLogin.getInstance().getMapTokens();
if (StringUtils.isEmpty(tokens.getUserSession()) || StringUtils.isEmpty(tokens.getSessionToken())) {
tokens = null;
if (!noMapTokenShowed) {
ActivityMixin.showToast(activity, res.getString(R.string.map_token_err));
noMapTokenShowed = true;
}
}
}
}
final SearchResult searchResult = ConnectorFactory.searchByViewport(mapView.getViewport().resize(0.8), tokens);
downloaded = true;
final Set<Geocache> result = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
CGeoMap.filter(result);
// update the caches
// first remove filtered out
final Set<String> filteredCodes = searchResult.getFilteredGeocodes();
Log.d("Filtering out " + filteredCodes.size() + " caches: " + filteredCodes.toString());
caches.removeAll(DataStore.loadCaches(filteredCodes, LoadFlags.LOAD_CACHE_ONLY));
DataStore.removeCaches(filteredCodes, EnumSet.of(RemoveFlag.CACHE));
// new collection type needs to remove first to refresh
caches.removeAll(result);
caches.addAll(result);
lastSearchResult = searchResult;
//render
displayExecutor.execute(new DisplayRunnable(this));
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
/**
* Thread to Display (down)loaded caches. Started by {@link LoadRunnable} and {@link DownloadRunnable}
*/
private static class DisplayRunnable extends DoRunnable {
public DisplayRunnable(@NonNull final CGeoMap map) {
super(map);
}
@Override
public void runWithMap(final CGeoMap map) {
map.doDisplayRun();
}
}
private void doDisplayRun() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
// display caches
final List<Geocache> cachesToDisplay = caches.getAsList();
final List<Waypoint> waypointsToDisplay = new ArrayList<>(waypoints);
final List<CachesOverlayItemImpl> itemsToDisplay = new ArrayList<>();
if (!cachesToDisplay.isEmpty()) {
// Only show waypoints for single view or setting
// when less than showWaypointsthreshold Caches shown
if (mapMode == MapMode.SINGLE || (cachesCnt < Settings.getWayPointsThreshold())) {
for (final Waypoint waypoint : waypointsToDisplay) {
if (waypoint == null || waypoint.getCoords() == null) {
continue;
}
itemsToDisplay.add(getWaypointItem(waypoint));
}
}
for (final Geocache cache : cachesToDisplay) {
if (cache == null || cache.getCoords() == null) {
continue;
}
itemsToDisplay.add(getCacheItem(cache));
}
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
} else {
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS);
}
}
private void displayPoint(final Geopoint coords) {
final Waypoint waypoint = new Waypoint("some place", waypointTypeIntent != null ? waypointTypeIntent : WaypointType.WAYPOINT, false);
waypoint.setCoords(coords);
final CachesOverlayItemImpl item = getWaypointItem(waypoint);
overlayCaches.updateItems(item);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
displayHandler.sendEmptyMessage(UPDATE_TITLE);
cachesCnt = 1;
}
private static abstract class DoRunnable implements Runnable {
private final WeakReference<CGeoMap> mapRef;
protected DoRunnable(@NonNull final CGeoMap map) {
mapRef = new WeakReference<>(map);
}
@Override
final public void run() {
final CGeoMap map = mapRef.get();
if (map != null) {
runWithMap(map);
}
}
abstract protected void runWithMap(final CGeoMap map);
}
/**
* store caches, invoked by "store offline" menu item
*
* @param listId
* the list to store the caches in
*/
private void storeCaches(final List<String> geocodes, final int listId) {
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler();
waitDialog = new ProgressDialog(activity);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage());
waitDialog.setMax(detailTotal);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(final DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
} catch (final Exception e) {
Log.e("CGeoMap.storeCaches.onCancel", e);
}
}
});
final float etaTime = detailTotal * 7.0f / 60.0f;
final int roundedEta = Math.round(etaTime);
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta));
}
waitDialog.show();
detailProgressTime = System.currentTimeMillis();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listId);
loadDetailsThread.start();
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
final private CancellableHandler handler;
final private List<String> geocodes;
final private int listId;
public LoadDetails(final CancellableHandler handler, final List<String> geocodes, final int listId) {
this.handler = handler;
this.geocodes = geocodes;
this.listId = listId;
}
public void stopIt() {
handler.cancel();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
for (final String geocode : geocodes) {
try {
if (handler.isCancelled()) {
break;
}
if (!DataStore.isOffline(geocode, null)) {
Geocache.storeCache(null, geocode, listId, false, handler);
}
} catch (final Exception e) {
Log.e("CGeoMap.LoadDetails.run", e);
} finally {
// one more cache over
detailProgress++;
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
}
// we're done
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
private static synchronized void filter(final Collection<Geocache> caches) {
final boolean excludeMine = Settings.isExcludeMyCaches();
final boolean excludeDisabled = Settings.isExcludeDisabledCaches();
final List<Geocache> removeList = new ArrayList<>();
for (final Geocache cache : caches) {
if ((excludeMine && cache.isFound()) || (excludeMine && cache.isOwner()) || (excludeDisabled && cache.isDisabled()) || (excludeDisabled && cache.isArchived())) {
removeList.add(cache);
}
}
caches.removeAll(removeList);
}
private static boolean mapMoved(final Viewport referenceViewport, final Viewport newViewport) {
return Math.abs(newViewport.getLatitudeSpan() - referenceViewport.getLatitudeSpan()) > 50e-6 ||
Math.abs(newViewport.getLongitudeSpan() - referenceViewport.getLongitudeSpan()) > 50e-6 ||
Math.abs(newViewport.center.getLatitude() - referenceViewport.center.getLatitude()) > referenceViewport.getLatitudeSpan() / 4 ||
Math.abs(newViewport.center.getLongitude() - referenceViewport.center.getLongitude()) > referenceViewport.getLongitudeSpan() / 4;
}
// center map to desired location
private void centerMap(final Geopoint coords) {
if (coords == null) {
return;
}
final MapControllerImpl mapController = mapView.getMapController();
final GeoPointImpl target = makeGeoPoint(coords);
if (alreadyCentered) {
mapController.animateTo(target);
} else {
mapController.setCenter(target);
}
alreadyCentered = true;
}
// move map to view results of searchIntent
private void centerMap(final String geocodeCenter, final SearchResult searchCenter, final Geopoint coordsCenter, final int[] mapState) {
final MapControllerImpl mapController = mapView.getMapController();
if (!centered && mapState != null) {
try {
mapController.setCenter(mapItemFactory.getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6)));
setZoom(mapState[2]);
} catch (final RuntimeException e) {
Log.e("centermap", e);
}
centered = true;
alreadyCentered = true;
} else if (!centered && (geocodeCenter != null || searchIntent != null)) {
try {
Viewport viewport = null;
if (geocodeCenter != null) {
viewport = DataStore.getBounds(geocodeCenter);
} else if (searchCenter != null) {
viewport = DataStore.getBounds(searchCenter.getGeocodes());
}
if (viewport == null) {
return;
}
mapController.setCenter(mapItemFactory.getGeoPointBase(viewport.center));
if (viewport.getLatitudeSpan() != 0 && viewport.getLongitudeSpan() != 0) {
mapController.zoomToSpan((int) (viewport.getLatitudeSpan() * 1e6), (int) (viewport.getLongitudeSpan() * 1e6));
}
} catch (final RuntimeException e) {
Log.e("centermap", e);
}
centered = true;
alreadyCentered = true;
} else if (!centered && coordsCenter != null) {
try {
mapController.setCenter(makeGeoPoint(coordsCenter));
} catch (final Exception e) {
Log.e("centermap", e);
}
centered = true;
alreadyCentered = true;
}
}
// switch My Location button image
private void switchMyLocationButton() {
myLocSwitch.setChecked(followMyLocation);
if (followMyLocation) {
myLocationInMiddle(app.currentGeo());
}
}
// set my location listener
private static class MyLocationListener implements View.OnClickListener {
private final WeakReference<CGeoMap> mapRef;
public MyLocationListener(@NonNull final CGeoMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void onClick(final View view) {
final CGeoMap map = mapRef.get();
if (map != null) {
map.onFollowMyLocationClicked();
}
}
}
private void onFollowMyLocationClicked() {
followMyLocation = !followMyLocation;
switchMyLocationButton();
}
public static class MapDragListener implements OnMapDragListener {
private final WeakReference<CGeoMap> mapRef;
public MapDragListener(@NonNull final CGeoMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void onDrag() {
final CGeoMap map = mapRef.get();
if (map != null) {
map.onDrag();
}
}
}
private void onDrag() {
if (followMyLocation) {
followMyLocation = false;
switchMyLocationButton();
}
}
// make geopoint
private GeoPointImpl makeGeoPoint(final Geopoint coords) {
return mapItemFactory.getGeoPointBase(coords);
}
@Override
public View makeView() {
final ImageView imageView = new ImageView(activity);
imageView.setScaleType(ScaleType.CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return imageView;
}
private static Intent newIntent(final Context context) {
return new Intent(context, Settings.getMapProvider().getMapClass());
}
public static void startActivitySearch(final Activity fromActivity, final SearchResult search, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_SEARCH, search);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.LIST);
mapIntent.putExtra(EXTRAS_LIVE_ENABLED, false);
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityLiveMap(final Activity fromActivity) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.LIVE);
mapIntent.putExtra(EXTRAS_LIVE_ENABLED, Settings.isLiveMap());
fromActivity.startActivity(mapIntent);
}
public static void startActivityCoords(final Activity fromActivity, final Geopoint coords, final WaypointType type, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.COORDS);
mapIntent.putExtra(EXTRAS_LIVE_ENABLED, false);
mapIntent.putExtra(EXTRAS_COORDS, coords);
if (type != null) {
mapIntent.putExtra(EXTRAS_WPTTYPE, type.id);
}
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityGeoCode(final Activity fromActivity, final String geocode) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.SINGLE);
mapIntent.putExtra(EXTRAS_LIVE_ENABLED, false);
mapIntent.putExtra(EXTRAS_GEOCODE, geocode);
mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode);
fromActivity.startActivity(mapIntent);
}
public static void markCacheAsDirty(final String geocode) {
dirtyCaches.add(geocode);
}
private CachesOverlayItemImpl getCacheItem(final Geocache cache) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(cache, cache.applyDistanceRule());
item.setMarker(MapUtils.getCacheItem(getResources(), cache));
return item;
}
private CachesOverlayItemImpl getWaypointItem(final Waypoint waypoint) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(waypoint, waypoint.getWaypointType().applyDistanceRule());
final Drawable marker = getResources().getDrawable(!waypoint.isVisited() ? R.drawable.marker : R.drawable.marker_transparent);
final Drawable[] layers = new Drawable[] {
marker,
getResources().getDrawable(waypoint.getWaypointType().markerId)
};
final LayerDrawable ld = new LayerDrawable(layers);
if (layers[0].getIntrinsicWidth() > 40) {
ld.setLayerInset(1, 9, 12, 10, 13);
} else {
ld.setLayerInset(1, 9, 12, 8, 12);
}
item.setMarker(ld);
return item;
}
}
|
package com.rogoapp;
import java.lang.reflect.InvocationTargetException;
import com.rogoapp.auth.AccountAuthenticator;
import com.rogoapp.auth.RogoAuthenticatorActivity;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler; // Wait for specified time before going to main screen
public class SplashScreen extends Activity {
static int SPLASH_TIME_OUT = 1500; // Splash screen timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/* Showing splash screen with timer */
public void run() {
/* Start main activity after splash screen over */
AccountManager am = AccountManager.get(getBaseContext());
android.accounts.Account[] accounts = am.getAccountsByType(RogoAuthenticatorActivity.PARAM_AUTHTOKEN_TYPE);
// AccountAuthenticatorResponse response = new AccountAuthenticatorResponse(null);
// AccountAuthenticator auth = new AccountAuthenticator(MyApplication.getAppContext());
// Bundle token = null;
// try {
// token = auth.getAuthToken(response, accounts[0], RogoAuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, null);
// } catch (NetworkErrorException e) {
// token = null;
// e.printStackTrace();
String token = "";
try{
if(accounts != null)
token = am.peekAuthToken(accounts[0], RogoAuthenticatorActivity.PARAM_AUTHTOKEN_TYPE);
}catch(Exception e){
e.printStackTrace();
}
Intent i;
if(token != null && token != ""){
i = new Intent(SplashScreen.this, MainScreenActivity.class);
}
else{
i = new Intent(SplashScreen.this,RogoAuthenticatorActivity.class);
}
startActivity(i);
// close the activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
|
package com.phonegap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin {
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private Uri imageUri; // Uri of captured image
public String callbackId;
/**
* Constructor.
*/
public CameraLauncher() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackId = callbackId;
try {
if (action.equals("takePicture")) {
int destType = DATA_URL;
if (args.length() > 1) {
destType = args.getInt(1);
}
int srcType = CAMERA;
if (args.length() > 2) {
srcType = args.getInt(2);
}
if (srcType == CAMERA) {
this.takePicture(args.getInt(0), destType);
}
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(args.getInt(0), srcType, destType);
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
// LOCAL METHODS
/**
* Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned
* in PhonegapActivity.onActivityResult, which forwards the result to this.onActivityResult.
*
* The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag
* img.src=result;
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return.
*/
public void takePicture(int quality, int returnType) {
this.mQuality = quality;
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned
// TODO: What if there isn't any external storage?
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
}
/**
* Get image from photo library.
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from.
* @param returnType Set the type of image to return.
*/
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int quality, int srcType, int returnType) {
this.mQuality = quality;
Intent intent = new Intent();
/**
* Called when the camera view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Read in bitmap of captured image
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
}
// If sending filename back
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
System.out.println("Can't write to external media storage.");
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
System.out.println("Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If sending base64 image back
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
this.processPicture(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
// If sending filename back
else if (destType == FILE_URI) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
}
}
catch(Exception e) {
this.failPicture("Error compressing image.");
}
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
}
|
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.components.salesforce.runtime;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.namespace.QName;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.api.container.RuntimeContainer;
import org.talend.components.api.exception.ComponentException;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.common.runtime.ProxyPropertiesRuntimeHelper;
import org.talend.components.salesforce.SalesforceConnectionProperties;
import org.talend.components.salesforce.SalesforceDefinition;
import org.talend.components.salesforce.SalesforceProvideConnectionProperties;
import org.talend.components.salesforce.common.SalesforceRuntimeSourceOrSink;
import org.talend.components.salesforce.connection.oauth.SalesforceOAuthConnection;
import org.talend.components.salesforce.runtime.common.ConnectionHolder;
import org.talend.components.salesforce.runtime.common.SalesforceConstant;
import org.talend.components.salesforce.runtime.common.SalesforceRuntimeCommon;
import org.talend.components.salesforce.schema.SalesforceSchemaHelper;
import org.talend.components.salesforce.soql.FieldDescription;
import org.talend.components.salesforce.soql.SoqlQuery;
import org.talend.components.salesforce.soql.SoqlQueryBuilder;
import org.talend.daikon.NamedThing;
import org.talend.daikon.SimpleNamedThing;
import org.talend.daikon.avro.AvroUtils;
import org.talend.daikon.properties.ValidationResult;
import org.talend.daikon.runtime.RuntimeInfo;
import org.talend.daikon.runtime.RuntimeUtil;
import org.talend.daikon.sandbox.SandboxedInstance;
import com.sforce.async.AsyncApiException;
import com.sforce.async.BulkConnection;
import com.sforce.soap.partner.DescribeGlobalResult;
import com.sforce.soap.partner.DescribeGlobalSObjectResult;
import com.sforce.soap.partner.DescribeSObjectResult;
import com.sforce.soap.partner.GetUserInfoResult;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.SessionRenewer;
public class SalesforceSourceOrSink implements SalesforceRuntimeSourceOrSink, SalesforceSchemaHelper<Schema> {
private transient static final Logger LOG = LoggerFactory.getLogger(SalesforceSourceOrSink.class);
protected SalesforceProvideConnectionProperties properties;
private transient static final Schema DEFAULT_GUESS_SCHEMA_TYPE = AvroUtils._string();
protected static final String KEY_CONNECTION = "Connection";
private String sessionFilePath;
private String sessionId;
private String serviceEndPoint;
@Override
public ValidationResult initialize(RuntimeContainer container, ComponentProperties properties) {
this.properties = (SalesforceProvideConnectionProperties) properties;
return ValidationResult.OK;
}
@Override
public ValidationResult validate(RuntimeContainer container) {
ValidationResult vr = new ValidationResult();
try {
connect(container);
} catch (IOException ex) {
return SalesforceRuntimeCommon.exceptionToValidationResult(ex);
}
return vr;
}
public static ValidationResult validateConnection(SalesforceProvideConnectionProperties properties) {
ClassLoader classLoader = SalesforceDefinition.class.getClassLoader();
RuntimeInfo runtimeInfo = SalesforceDefinition.getCommonRuntimeInfo(SalesforceSourceOrSink.class.getCanonicalName());
try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClassWithCurrentJVMProperties(runtimeInfo,
classLoader)) {
SalesforceSourceOrSink ss = (SalesforceSourceOrSink) sandboxedInstance.getInstance();
ss.initialize(null, (ComponentProperties) properties);
return ss.validate(null);
}
}
/**
* If referenceComponentId is not null, it should return the reference connection properties
*/
public SalesforceConnectionProperties getConnectionProperties() {
SalesforceConnectionProperties connectionProperties = properties.getConnectionProperties();
if (connectionProperties.getReferencedComponentId() != null) {
connectionProperties = connectionProperties.getReferencedConnectionProperties();
}
return connectionProperties;
}
protected BulkConnection connectBulk(ConnectorConfig config) throws ComponentException {
final SalesforceConnectionProperties connProps = getConnectionProperties();
/*
* When PartnerConnection is instantiated, a login is implicitly executed and, if successful, a valid session is
* stored in the ConnectorConfig instance. Use this key to initialize a BulkConnection:
*/
ConnectorConfig bulkConfig = new ConnectorConfig();
setProxy(bulkConfig);
bulkConfig.setSessionId(config.getSessionId());
// For session renew
bulkConfig.setSessionRenewer(config.getSessionRenewer());
bulkConfig.setUsername(config.getUsername());
bulkConfig.setPassword(config.getPassword());
/*
* The endpoint for the Bulk API service is the same as for the normal SOAP uri until the /Soap/ part. From here
* it's '/async/versionNumber'
*/
String soapEndpoint = config.getServiceEndpoint();
// Service endpoint should be like this:
String apiVersion = soapEndpoint.substring(soapEndpoint.lastIndexOf("/services/Soap/u/") + 17);
apiVersion = apiVersion.substring(0, apiVersion.indexOf("/"));
String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion;
bulkConfig.setRestEndpoint(restEndpoint);
// This should only be false when doing debugging.
bulkConfig.setCompression(connProps.needCompression.getValue());
bulkConfig.setTraceMessage(connProps.httpTraceMessage.getValue());
bulkConfig.setValidateSchema(false);
try {
return new BulkConnection(bulkConfig);
} catch (AsyncApiException e) {
throw new ComponentException(e);
}
}
/**
* Create a connection with specified connector configuration
*
* @param config connector configuration with endpoint/userId/password
* @param openNewSession whether need to create new session
* @return PartnerConnection object with correct session id
* @throws ConnectionException create connection fails
*/
protected PartnerConnection doConnection(ConnectorConfig config, boolean openNewSession) throws ConnectionException {
if (!openNewSession) {
config.setSessionId(this.sessionId);
config.setServiceEndpoint(this.serviceEndPoint);
} else {
SalesforceConnectionProperties connProps = getConnectionProperties();
String endpoint = connProps.endpoint.getStringValue();
endpoint = StringUtils.strip(endpoint, "\"");
if (SalesforceConnectionProperties.LoginType.OAuth.equals(connProps.loginType.getValue())) {
SalesforceOAuthConnection oauthConnection = new SalesforceOAuthConnection(connProps.oauth, endpoint,
connProps.apiVersion.getValue());
oauthConnection.login(config);
} else {
config.setAuthEndpoint(endpoint);
}
}
PartnerConnection connection = new PartnerConnection(config);
if (openNewSession && isReuseSession()) {
this.sessionId = config.getSessionId();
this.serviceEndPoint = config.getServiceEndpoint();
if (this.sessionId != null && this.serviceEndPoint != null) {
// update session file with current sessionId/serviceEndPoint
setupSessionProperties(connection);
}
}
return connection;
}
protected ConnectionHolder connect(RuntimeContainer container) throws IOException {
SalesforceRuntimeCommon.enableTLSv11AndTLSv12ForJava7();
final ConnectionHolder ch = new ConnectionHolder();
SalesforceConnectionProperties connProps = properties.getConnectionProperties();
String refComponentId = connProps.getReferencedComponentId();
Object sharedConn = null;
// Using another component's connection
if (refComponentId != null) {
// In a runtime container
if (container != null) {
sharedConn = container.getComponentData(refComponentId, KEY_CONNECTION);
if (sharedConn != null) {
if (sharedConn instanceof PartnerConnection) {
ch.connection = (PartnerConnection) sharedConn;
} else if (sharedConn instanceof BulkConnection) {
ch.bulkConnection = (BulkConnection) sharedConn;
}
return ch;
}
throw new IOException("Referenced component: " + refComponentId + " not connected");
}
// Design time
connProps = connProps.getReferencedConnectionProperties();
}
// FIXME add back reffed connection
ConnectorConfig config = new ConnectorConfig();
config.setUsername(StringUtils.strip(connProps.userPassword.userId.getStringValue(), "\""));
String password = StringUtils.strip(connProps.userPassword.password.getStringValue(), "\"");
String securityKey = StringUtils.strip(connProps.userPassword.securityKey.getStringValue(), "\"");
if (!StringUtils.isEmpty(securityKey)) {
password = password + securityKey;
}
config.setPassword(password);
setProxy(config);
// Notes on how to test this
config.setSessionRenewer(new SessionRenewer() {
@Override
public SessionRenewalHeader renewSession(ConnectorConfig connectorConfig) throws ConnectionException {
LOG.debug("renewing session...");
SessionRenewalHeader header = new SessionRenewalHeader();
connectorConfig.setSessionId(null);
PartnerConnection connection = doConnection(connectorConfig, true);
// update the connection session header
ch.connection.setSessionHeader(connection.getSessionHeader().getSessionId());
header.name = new QName("urn:partner.soap.sforce.com", "SessionHeader");
header.headerElement = connection.getSessionHeader();
LOG.debug("session renewed!");
return header;
}
});
if (connProps.timeout.getValue() > 0) {
config.setConnectionTimeout(connProps.timeout.getValue());
}
config.setCompression(connProps.needCompression.getValue());
if (false) {
config.setTraceMessage(true);
}
config.setUseChunkedPost(connProps.httpChunked.getValue());
config.setValidateSchema(false);
try {
// Get session from session file or new connection
if (isReuseSession()) {
Properties properties = getSessionProperties();
if (properties != null) {
this.sessionId = properties.getProperty(SalesforceConstant.SESSION_ID);
this.serviceEndPoint = properties.getProperty(SalesforceConstant.SERVICE_ENDPOINT);
}
}
if (this.sessionId != null && this.serviceEndPoint != null) {
ch.connection = doConnection(config, false);
} else {
ch.connection = doConnection(config, true);
}
if (ch.connection != null) {
String clientId = connProps.clientId.getStringValue();
if (clientId != null) {
// Need the test.
ch.connection.setCallOptions(clientId, null);
}
}
if (connProps.bulkConnection.getValue()) {
ch.bulkConnection = connectBulk(ch.connection.getConfig());
sharedConn = ch.bulkConnection;
} else {
sharedConn = ch.connection;
}
if (container != null) {
container.setComponentData(container.getCurrentComponentId(), KEY_CONNECTION, sharedConn);
}
return ch;
} catch (ConnectionException e) {
throw new IOException(e);
}
}
public static List<NamedThing> getSchemaNames(RuntimeContainer container, SalesforceProvideConnectionProperties properties)
throws IOException {
ClassLoader classLoader = SalesforceDefinition.class.getClassLoader();
RuntimeInfo runtimeInfo = SalesforceDefinition.getCommonRuntimeInfo(SalesforceSourceOrSink.class.getCanonicalName());
try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClassWithCurrentJVMProperties(runtimeInfo,
classLoader)) {
SalesforceSourceOrSink ss = (SalesforceSourceOrSink) sandboxedInstance.getInstance();
ss.initialize(null, (ComponentProperties) properties);
try {
ss.connect(container);
return ss.getSchemaNames(container);
} catch (Exception ex) {
throw new ComponentException(SalesforceRuntimeCommon.exceptionToValidationResult(ex));
}
}
}
@Override
public List<NamedThing> getSchemaNames(RuntimeContainer container) throws IOException {
return getSchemaNames(connect(container).connection);
}
protected List<NamedThing> getSchemaNames(PartnerConnection connection) throws IOException {
List<NamedThing> returnList = new ArrayList<>();
DescribeGlobalResult result = null;
try {
result = connection.describeGlobal();
} catch (ConnectionException e) {
throw new ComponentException(e);
}
DescribeGlobalSObjectResult[] objects = result.getSobjects();
for (DescribeGlobalSObjectResult obj : objects) {
LOG.debug("module label: " + obj.getLabel() + " name: " + obj.getName());
returnList.add(new SimpleNamedThing(obj.getName(), obj.getLabel()));
}
return returnList;
}
public static Schema getSchema(RuntimeContainer container, SalesforceProvideConnectionProperties properties, String module)
throws IOException {
ClassLoader classLoader = SalesforceDefinition.class.getClassLoader();
RuntimeInfo runtimeInfo = SalesforceDefinition.getCommonRuntimeInfo(SalesforceSourceOrSink.class.getCanonicalName());
try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClassWithCurrentJVMProperties(runtimeInfo,
classLoader)) {
SalesforceSourceOrSink ss = (SalesforceSourceOrSink) sandboxedInstance.getInstance();
ss.initialize(null, (ComponentProperties) properties);
PartnerConnection connection = null;
try {
connection = ss.connect(container).connection;
} catch (IOException ex) {
throw new ComponentException(SalesforceRuntimeCommon.exceptionToValidationResult(ex));
}
return ss.getSchema(connection, module);
}
}
@Override
public Schema getEndpointSchema(RuntimeContainer container, String schemaName) throws IOException {
return getSchema(connect(container).connection, schemaName);
}
protected Schema getSchema(PartnerConnection connection, String module) throws IOException {
try {
DescribeSObjectResult[] describeSObjectResults = new DescribeSObjectResult[0];
describeSObjectResults = connection.describeSObjects(new String[] { module });
return SalesforceAvroRegistry.get().inferSchema(describeSObjectResults[0]);
} catch (ConnectionException e) {
throw new IOException(e);
}
}
private synchronized void setProxy(ConnectorConfig config) {
final ProxyPropertiesRuntimeHelper proxyHelper = new ProxyPropertiesRuntimeHelper(
properties.getConnectionProperties().proxy);
resetAuthenticator();
if (proxyHelper.getProxyHost() != null) {
if (proxyHelper.getSocketProxy() != null) {
config.setProxy(proxyHelper.getSocketProxy());
} else {
config.setProxy(proxyHelper.getProxyHost(), Integer.parseInt(proxyHelper.getProxyPort()));
}
if (proxyHelper.getProxyUser() != null && proxyHelper.getProxyUser().length() > 0) {
config.setProxyUsername(proxyHelper.getProxyUser());
if (proxyHelper.getProxyPwd() != null && proxyHelper.getProxyPwd().length() > 0) {
config.setProxyPassword(proxyHelper.getProxyPwd());
setAuthenticator(proxyHelper.getProxyUser(), proxyHelper.getProxyPwd());
}
}
}
}
private void resetAuthenticator() {
Authenticator.setDefault(null);// null is a common value for this
}
private void setAuthenticator(final String username, final String password) {
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
/**
* Get the session properties instance
*
* @return session properties
* @throws ConnectionException connection disable during get user information
*/
protected Properties getSessionProperties() throws ConnectionException {
File sessionFile = new File(sessionFilePath);
try {
if (sessionFile.exists()) {
FileInputStream sessionInput = new FileInputStream(sessionFile);
try {
Properties sessionProp = new Properties();
sessionProp.load(sessionInput);
int maxValidSeconds = Integer.valueOf(sessionProp.getProperty(SalesforceConstant.MAX_VALID_SECONDS));
// Check whether the session is timeout
if (maxValidSeconds > ((System.currentTimeMillis() - sessionFile.lastModified()) / 1000)) {
return sessionProp;
}
} finally {
sessionInput.close();
}
}
} catch (IOException e) {
throw new ConnectionException("Reuse session fails!", e);
}
return null;
}
/**
* Save session to target file
*
* @param connection which you want to saved information
* @throws IOException error during create or write session file
* @throws ConnectionException connection disable during get user information
*/
protected void setupSessionProperties(PartnerConnection connection) throws ConnectionException {
try {
GetUserInfoResult result = connection.getUserInfo();
File sessionFile = new File(sessionFilePath);
if (!sessionFile.exists()) {
File parentPath = sessionFile.getParentFile();
if (!parentPath.exists()) {
parentPath.mkdirs();
}
sessionFile.createNewFile();
}
FileOutputStream sessionOutput = null;
sessionOutput = new FileOutputStream(sessionFile);
Properties sessionProp = new Properties();
sessionProp.setProperty(SalesforceConstant.SESSION_ID, sessionId);
sessionProp.setProperty(SalesforceConstant.SERVICE_ENDPOINT, serviceEndPoint);
sessionProp.setProperty(SalesforceConstant.MAX_VALID_SECONDS, String.valueOf(result.getSessionSecondsValid()));
try {
sessionProp.store(sessionOutput, null);
} finally {
sessionOutput.close();
}
} catch (IOException e) {
throw new ConnectionException("Reuse session fails!", e);
}
}
/**
* Whether reuse session available
*/
protected boolean isReuseSession() {
SalesforceConnectionProperties connectionProperties = getConnectionProperties();
sessionFilePath = connectionProperties.sessionDirectory.getValue() + "/" + SalesforceConstant.SESSION_FILE_PREFX
+ connectionProperties.userPassword.userId.getValue();
return (SalesforceConnectionProperties.LoginType.Basic == connectionProperties.loginType.getValue())
&& connectionProperties.reuseSession.getValue() && !StringUtils.isEmpty(sessionFilePath);
}
@Override
public Schema guessSchema(String soqlQuery) throws IOException {
SoqlQuery query = SoqlQuery.getInstance();
query.init(soqlQuery);
SchemaBuilder.FieldAssembler fieldAssembler = SchemaBuilder.record("GuessedSchema").fields();
DescribeSObjectResult describeSObjectResult = null;
try {
describeSObjectResult = connect(null).connection.describeSObject(query.getDrivingEntityName());
} catch (ConnectionException e) {
throw new RuntimeException(e.getMessage());
}
Schema entitySchema = SalesforceAvroRegistry.get().inferSchema(describeSObjectResult);
for (FieldDescription fieldDescription : query.getFieldDescriptions()) {
Schema.Field schemaField = entitySchema.getField(fieldDescription.getSimpleName());
SchemaBuilder.FieldBuilder builder = fieldAssembler.name(fieldDescription.getFullName());
Map<String, Object> props = schemaField.getObjectProps();
for (Map.Entry<String, Object> entry : props.entrySet()) {
builder.prop(entry.getKey(), String.valueOf(entry.getValue()));
}
Schema fieldType = null;
if (schemaField != null) {
fieldType = schemaField.schema();
} else {
fieldType = DEFAULT_GUESS_SCHEMA_TYPE;
}
builder.type(fieldType).noDefault();
}
return (Schema) fieldAssembler.endRecord();
}
/**
* Gets SOQL query
*
* @param schema which fields used for SOQL query building
* @param entityName is the module name
*/
@Override
public String guessQuery(Schema schema, String entityName) {
return new SoqlQueryBuilder(schema, entityName).buildSoqlQuery();
}
}
|
package org.innovateuk.ifs.competitionsetup.eligibility.populator;
import org.innovateuk.ifs.competition.form.enumerable.ResearchParticipationAmount;
import org.innovateuk.ifs.competition.resource.CollaborationLevel;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
import org.innovateuk.ifs.competitionsetup.core.form.CompetitionSetupForm;
import org.innovateuk.ifs.competitionsetup.core.populator.CompetitionSetupFormPopulator;
import org.innovateuk.ifs.competitionsetup.core.util.CompetitionUtils;
import org.innovateuk.ifs.competitionsetup.eligibility.form.EligibilityForm;
import org.innovateuk.ifs.finance.resource.GrantClaimMaximumResource;
import org.innovateuk.ifs.finance.service.GrantClaimMaximumRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.isBlank;
/**
* Form populator for the eligibility competition setup section.
*/
@Service
public class EligibilityFormPopulator implements CompetitionSetupFormPopulator {
private GrantClaimMaximumRestService grantClaimMaximumRestService;
public EligibilityFormPopulator(GrantClaimMaximumRestService grantClaimMaximumRestService) {
this.grantClaimMaximumRestService = grantClaimMaximumRestService;
}
@Override
public CompetitionSetupSection sectionToFill() {
return CompetitionSetupSection.ELIGIBILITY;
}
@Override
public CompetitionSetupForm populateForm(CompetitionResource competitionResource) {
EligibilityForm competitionSetupForm = new EligibilityForm();
competitionSetupForm.setResearchCategoryId(competitionResource.getResearchCategories());
ResearchParticipationAmount amount = ResearchParticipationAmount.fromAmount(competitionResource.getMaxResearchRatio());
if (amount != null) {
competitionSetupForm.setResearchParticipationAmountId(amount.getId());
}
competitionSetupForm.setMultipleStream("no");
CollaborationLevel level = competitionResource.getCollaborationLevel();
if (level != null) {
competitionSetupForm.setSingleOrCollaborative(level.getCode());
}
List<Long> organisationTypes = competitionResource.getLeadApplicantTypes();
if (organisationTypes != null) {
competitionSetupForm.setLeadApplicantTypes(organisationTypes);
}
competitionSetupForm.setResubmission(CompetitionUtils.booleanToText(competitionResource.getResubmission()));
Boolean overrideFundingRuleSet = getOverrideFundingRulesSet(competitionResource, competitionSetupForm);
competitionSetupForm.setOverrideFundingRules(overrideFundingRuleSet);
if (overrideFundingRuleSet != null && overrideFundingRuleSet) {
competitionSetupForm.setFundingLevelPercentage(getFundingLevelPercentage(competitionResource));
}
return competitionSetupForm;
}
private Boolean getOverrideFundingRulesSet(CompetitionResource competitionResource,
EligibilityForm eligibilityForm) {
if (!isFirstTimeInForm(eligibilityForm)) {
return grantClaimMaximumRestService.isMaximumFundingLevelOverridden(competitionResource.getId()).getSuccess();
}
return null;
}
private boolean isFirstTimeInForm(EligibilityForm eligibilityForm) {
return "no".equals(eligibilityForm.getMultipleStream())
&& eligibilityForm.getResearchCategoryId().isEmpty()
&& (eligibilityForm.getSingleOrCollaborative() == null)
&& eligibilityForm.getLeadApplicantTypes().isEmpty()
&& isBlank(eligibilityForm.getResubmission());
}
private Integer getFundingLevelPercentage(CompetitionResource competition) {
Optional<GrantClaimMaximumResource> overriddenGcm = competition.getGrantClaimMaximums()
.stream()
.map(id -> grantClaimMaximumRestService.getGrantClaimMaximumById(id).getSuccess())
.filter(gcm -> gcm.getOrganisationType().getId().equals(OrganisationTypeEnum.BUSINESS.getId()))
.findFirst();
return overriddenGcm.get().getMaximum();
}
}
|
package eu.dnetlib.iis.workflows.citationmatching.direct;
import java.io.IOException;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import pl.edu.icm.sparkutils.avro.SparkAvroLoader;
import pl.edu.icm.sparkutils.avro.SparkAvroSaver;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import eu.dnetlib.iis.citationmatching.direct.schemas.Citation;
import eu.dnetlib.iis.citationmatching.direct.schemas.DocumentMetadata;
import eu.dnetlib.iis.transformers.metadatamerger.schemas.ExtractedDocumentMetadataMergedWithOriginal;
import eu.dnetlib.iis.workflows.citationmatching.direct.converter.DirectCitationToCitationConverter;
import eu.dnetlib.iis.workflows.citationmatching.direct.converter.DocumentToDirectCitationMetadataConverter;
import eu.dnetlib.iis.workflows.citationmatching.direct.model.IdWithPosition;
import eu.dnetlib.iis.workflows.citationmatching.direct.service.ExternalIdCitationMatcher;
import eu.dnetlib.iis.workflows.citationmatching.direct.service.PickFirstDocumentFunction;
import eu.dnetlib.iis.workflows.citationmatching.direct.service.PickResearchArticleDocumentFunction;
public class CitationMatchingDirectJob {
private static DocumentToDirectCitationMetadataConverter documentToDirectCitationMetadataConverter = new DocumentToDirectCitationMetadataConverter();
private static ExternalIdCitationMatcher externalIdCitationMatcher = new ExternalIdCitationMatcher();
private static DirectCitationToCitationConverter directCitationToCitationConverter = new DirectCitationToCitationConverter();
public static void main(String[] args) throws IOException {
CitationMatchingDirectJobParameters params = new CitationMatchingDirectJobParameters();
JCommander jcommander = new JCommander(params);
jcommander.parse(args);
SparkConf conf = new SparkConf();
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.kryo.registrator", "eu.dnetlib.iis.core.spark.AvroCompatibleKryoRegistrator");
try (JavaSparkContext sc = new JavaSparkContext(conf)) {
JavaRDD<ExtractedDocumentMetadataMergedWithOriginal> documents = SparkAvroLoader.loadJavaRDD(sc, params.inputAvroPath, ExtractedDocumentMetadataMergedWithOriginal.class);
JavaRDD<DocumentMetadata> simplifiedDocuments = documents.map(document -> documentToDirectCitationMetadataConverter.convert(document));
simplifiedDocuments = simplifiedDocuments.cache();
JavaRDD<Citation> directDoiCitations = externalIdCitationMatcher.matchCitations(simplifiedDocuments, "doi", new PickFirstDocumentFunction());
JavaRDD<Citation> directPmidCitations = externalIdCitationMatcher.matchCitations(simplifiedDocuments, "pmid", new PickResearchArticleDocumentFunction());
JavaRDD<Citation> directCitations = mergeCitations(directDoiCitations, directPmidCitations);
JavaRDD<eu.dnetlib.iis.common.citations.schemas.Citation> citations =
directCitations.map(directCitation -> directCitationToCitationConverter.convert(directCitation));
SparkAvroSaver.saveJavaRDD(citations, eu.dnetlib.iis.common.citations.schemas.Citation.SCHEMA$, params.outputAvroPath);
}
}
private static JavaRDD<Citation> mergeCitations(JavaRDD<Citation> directDoiCitations, JavaRDD<Citation> directPmidCitations) {
JavaPairRDD<IdWithPosition, Citation> directDoiCitationsWithKey = attachIdWithPositionKey(directDoiCitations);
JavaPairRDD<IdWithPosition, Citation> directPmidCitationsWithKey = attachIdWithPositionKey(directPmidCitations);
JavaRDD<Citation> directCitations = directDoiCitationsWithKey.fullOuterJoin(directPmidCitationsWithKey)
.map(x -> x._2._1.isPresent() ? x._2._1.get() : x._2._2.get() );
return directCitations;
}
private static JavaPairRDD<IdWithPosition, Citation> attachIdWithPositionKey(JavaRDD<Citation> directCitations) {
JavaPairRDD<IdWithPosition, Citation> directCitationsWithKey = directCitations
.keyBy(directCitation -> new IdWithPosition(directCitation.getSourceDocumentId().toString(), directCitation.getPosition()));
return directCitationsWithKey;
}
@Parameters(separators = "=")
private static class CitationMatchingDirectJobParameters {
@Parameter(names = "-inputAvroPath", required = true)
private String inputAvroPath;
@Parameter(names = "-outputAvroPath", required = true)
private String outputAvroPath;
}
}
|
package org.opencb.opencga.storage.hadoop.utils;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.parquet.hadoop.ParquetFileWriter;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.hadoop.io.HDFSIOConnector;
import org.opencb.opencga.storage.hadoop.variant.mr.VariantMapReduceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static org.opencb.opencga.core.common.IOUtils.humanReadableByteCount;
import static org.opencb.opencga.storage.hadoop.variant.HadoopVariantStorageOptions.MR_EXECUTOR_SSH_PASSWORD;
public abstract class AbstractHBaseDriver extends Configured implements Tool {
public static final String COUNTER_GROUP_NAME = "OPENCGA.HBASE";
public static final String COLUMNS_TO_COUNT = "columns_to_count";
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHBaseDriver.class);
protected String table;
public AbstractHBaseDriver() {
}
public AbstractHBaseDriver(Configuration conf) {
super(conf);
}
protected abstract String getJobName();
private Job newJob() throws IOException {
LOGGER.info("Create MR Job");
Job job = Job.getInstance(getConf(), getJobName());
job.getConfiguration().set(MRJobConfig.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, "true");
job.setJarByClass(AbstractHBaseDriver.class); // class that contains mapper
addJobConf(job, MRJobConfig.PRIORITY);
addJobConf(job, MRJobConfig.QUEUE_NAME);
addJobConf(job, MRJobConfig.MAP_MEMORY_MB);
addJobConf(job, MRJobConfig.REDUCE_MEMORY_MB);
addJobConf(job, MRJobConfig.MAP_CPU_VCORES);
addJobConf(job, MRJobConfig.REDUCE_CPU_VCORES);
addJobConf(job, MRJobConfig.JOB_RUNNING_MAP_LIMIT);
addJobConf(job, MRJobConfig.JOB_RUNNING_REDUCE_LIMIT);
addJobConf(job, MRJobConfig.TASK_TIMEOUT);
return job;
}
private void addJobConf(Job job, String key) {
String value = getParam(key);
if (StringUtils.isNotEmpty(value)) {
LOGGER.info("Configure MR job with {} = {}", key, value);
job.getConfiguration().set(key, value);
}
}
protected abstract void setupJob(Job job, String table) throws IOException;
protected void parseAndValidateParameters() throws IOException {
// Validate parameters CHECK
if (StringUtils.isEmpty(table)) {
throw new IllegalArgumentException("No table specified!");
}
}
protected String getUsage() {
return "Usage: " + getClass().getSimpleName() + " [generic options] <table> (<key> <value>)*";
}
protected String getParam(String key) {
return getParam(key, null);
}
protected String getParam(String key, String defaultValue) {
return VariantMapReduceUtil.getParam(getConf(), key, defaultValue, getClass());
}
protected int getFixedSizeArgs() {
return 1;
}
protected void preExecution() throws IOException, StorageEngineException {
}
protected void postExecution(Job job) throws IOException, StorageEngineException {
postExecution(job.isSuccessful());
}
protected void postExecution(boolean succeed) throws IOException, StorageEngineException {
}
protected void close() throws IOException, StorageEngineException {
}
@Override
public final int run(String[] args) throws Exception {
Configuration conf = getConf();
HBaseConfiguration.addHbaseResources(conf);
getConf().setClassLoader(AbstractHBaseDriver.class.getClassLoader());
if (configFromArgs(args)) {
return 1;
}
// Other user defined validations
parseAndValidateParameters();
// JOB setup
Job job = newJob();
setupJob(job, table);
preExecution();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
LOGGER.info("=================================================");
LOGGER.info("Execute " + getJobName());
LOGGER.info("=================================================");
boolean succeed = executeJob(job);
if (!succeed) {
LOGGER.error("error with job!");
}
LOGGER.info("=================================================");
LOGGER.info("Finish job " + getJobName());
LOGGER.info("Total time : " + TimeUtils.durationToString(stopWatch));
LOGGER.info("=================================================");
postExecution(job);
close();
return succeed ? 0 : 1;
}
private boolean configFromArgs(String[] args) {
int fixedSizeArgs = getFixedSizeArgs();
LOGGER.info(Arrays.toString(args));
boolean help = ArrayUtils.contains(args, "-h") || ArrayUtils.contains(args, "--help");
if (args.length < fixedSizeArgs || (args.length - fixedSizeArgs) % 2 != 0 || help) {
System.err.println(getUsage());
ToolRunner.printGenericCommandUsage(System.err);
if (!help) {
// System.err.println("Found " + Arrays.toString(args));
throw new IllegalArgumentException("Wrong number of arguments!");
}
return true;
}
// Get first other args to avoid overwrite the fixed position args.
for (int i = fixedSizeArgs; i < args.length; i = i + 2) {
getConf().set(args[i], args[i + 1]);
}
parseFixedParams(args);
return false;
}
protected void parseFixedParams(String[] args) {
table = args[0];
}
private boolean executeJob(Job job) throws IOException, InterruptedException, ClassNotFoundException {
Thread hook = new Thread(() -> {
try {
if (!job.isComplete()) {
job.killJob();
}
// onError();
} catch (IOException e) {
LOGGER.error("Error", e);
}
});
try {
Runtime.getRuntime().addShutdownHook(hook);
return job.waitForCompletion(true);
} finally {
Runtime.getRuntime().removeShutdownHook(hook);
}
}
protected boolean isLocal(Path path) {
return HDFSIOConnector.isLocal(path.toUri(), getConf());
}
protected Path getTempOutdir(String prefix) throws IOException {
return getTempOutdir(prefix, "");
}
protected Path getTempOutdir(String prefix, String suffix) throws IOException {
return getTempOutdir(prefix, suffix, false);
}
protected Path getTempOutdir(String prefix, String suffix, boolean ensureHdfs) throws IOException {
if (StringUtils.isEmpty(suffix)) {
suffix = "";
} else if (!suffix.startsWith(".")) {
suffix = "." + suffix;
}
// Be aware that
// > ABFS does not allow files or directories to end with a dot.
String fileName = prefix + "." + TimeUtils.getTime() + suffix;
Path tmpDir = new Path(getConf().get("hadoop.tmp.dir"));
if (ensureHdfs) {
FileSystem fileSystem = tmpDir.getFileSystem(getConf());
if (!fileSystem.getScheme().equals("hdfs")) {
LOGGER.info("Temporary directory is not in hdfs:// . Hdfs is required for this temporary file.");
LOGGER.info(" Default file system : " + fileSystem.getUri());
for (String nameServiceId : getConf().getTrimmedStringCollection("dfs.nameservices")) {
try {
Path hdfsTmpPath = new Path("hdfs", nameServiceId, "/tmp/");
FileSystem hdfsFileSystem = hdfsTmpPath.getFileSystem(getConf());
if (hdfsFileSystem != null) {
LOGGER.info("Change to file system : " + hdfsFileSystem.getUri());
tmpDir = hdfsTmpPath;
break;
}
} catch (Exception e) {
LOGGER.debug("This file system is not hdfs:// . Skip!", e);
}
}
}
}
LOGGER.info("Temporary directory: " + tmpDir.toUri());
return new Path(tmpDir, fileName);
}
protected Path getLocalOutput(Path outdir) throws IOException {
return getLocalOutput(outdir, () -> null);
}
protected Path getLocalOutput(Path outdir, Supplier<String> nameGenerator) throws IOException {
if (!isLocal(outdir)) {
throw new IllegalArgumentException("Outdir " + outdir + " is not in the local filesystem");
}
Path localOutput = outdir;
FileSystem localFs = localOutput.getFileSystem(getConf());
if (localFs.exists(localOutput)) {
if (localFs.isDirectory(localOutput)) {
String name = nameGenerator.get();
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Local output '" + localOutput + "' is a directory");
}
localOutput = new Path(localOutput, name);
} else {
throw new IllegalArgumentException("File '" + localOutput + "' already exists!");
}
} else {
if (!localFs.exists(localOutput.getParent())) {
Files.createDirectories(Paths.get(localOutput.getParent().toUri()));
// throw new IOException("No such file or directory: " + localOutput);
}
}
return localOutput;
}
protected void deleteTemporaryFile(Path outdir) throws IOException {
LOGGER.info("Delete temporary file " + outdir.toUri());
FileSystem fileSystem = outdir.getFileSystem(getConf());
fileSystem.delete(outdir, true);
fileSystem.cancelDeleteOnExit(outdir);
}
public class MapReduceOutputFile {
public static final String OUTPUT_PARAM = "output";
private final Supplier<String> nameGenerator;
private final String tempFilePrefix;
protected Path localOutput;
protected Path outdir;
public MapReduceOutputFile(Supplier<String> nameGenerator, String tempFilePrefix) throws IOException {
this.nameGenerator = nameGenerator;
this.tempFilePrefix = tempFilePrefix;
getOutputPath();
}
protected void getOutputPath() throws IOException {
String outdirStr = getParam(OUTPUT_PARAM);
if (StringUtils.isNotEmpty(outdirStr)) {
outdir = new Path(outdirStr);
if (isLocal(outdir)) {
localOutput = AbstractHBaseDriver.this.getLocalOutput(outdir, nameGenerator);
outdir = getTempOutdir(tempFilePrefix, localOutput.getName());
outdir.getFileSystem(getConf()).deleteOnExit(outdir);
}
if (localOutput != null) {
LOGGER.info(" * Outdir file: " + localOutput.toUri());
LOGGER.info(" * Temporary outdir file: " + outdir.toUri());
} else {
LOGGER.info(" * Outdir file: " + outdir.toUri());
}
}
}
public void postExecute(boolean succeed) throws IOException {
if (succeed) {
if (localOutput != null) {
concatMrOutputToLocal(outdir, localOutput);
}
}
if (localOutput != null) {
deleteTemporaryFile(outdir);
}
}
public Path getLocalOutput() {
return localOutput;
}
public Path getOutdir() {
return outdir;
}
}
/**
* Concatenate all generated files from a MapReduce job into one single local file.
*
* @param mrOutdir MapReduce output directory
* @param localOutput Local file
* @throws IOException on IOException
* @return List of copied files from HDFS
*/
protected List<Path> concatMrOutputToLocal(Path mrOutdir, Path localOutput) throws IOException {
return concatMrOutputToLocal(mrOutdir, localOutput, true);
}
/**
* Concatenate all generated files from a MapReduce job into one single local file.
*
* @param mrOutdir MapReduce output directory
* @param localOutput Local file
* @param removeExtraHeaders Remove header lines starting with "#" from all files but the first
* @throws IOException on IOException
* @return List of copied files from HDFS
*/
protected List<Path> concatMrOutputToLocal(Path mrOutdir, Path localOutput, boolean removeExtraHeaders) throws IOException {
// TODO: Allow copy output to any IOConnector
FileSystem fileSystem = mrOutdir.getFileSystem(getConf());
RemoteIterator<LocatedFileStatus> it = fileSystem.listFiles(mrOutdir, false);
List<Path> paths = new ArrayList<>();
while (it.hasNext()) {
LocatedFileStatus status = it.next();
Path path = status.getPath();
if (status.isFile()
&& !path.getName().equals(FileOutputCommitter.SUCCEEDED_FILE_NAME)
&& !path.getName().equals(FileOutputCommitter.PENDING_DIR_NAME)
&& !path.getName().equals(ParquetFileWriter.PARQUET_METADATA_FILE)
&& !path.getName().equals(ParquetFileWriter.PARQUET_COMMON_METADATA_FILE)
&& status.getLen() > 0) {
paths.add(path);
}
}
if (paths.size() == 0) {
LOGGER.warn("The MapReduce job didn't produce any output. This may not be expected.");
} else if (paths.size() == 1) {
LOGGER.info("Copy to local file " + paths.get(0).toUri() + " to " + localOutput.toUri());
fileSystem.copyToLocalFile(false, paths.get(0), localOutput);
LOGGER.info("File size : " + humanReadableByteCount(Files.size(Paths.get(localOutput.toUri())), false));
} else {
LOGGER.info("Concat and copy to local " + paths.size());
LOGGER.info(" Source : " + mrOutdir.toUri());
LOGGER.info(" Target : " + localOutput.toUri());
LOGGER.info("
try (FSDataOutputStream os = localOutput.getFileSystem(getConf()).create(localOutput)) {
for (int i = 0; i < paths.size(); i++) {
Path path = paths.get(i);
LOGGER.info("Concat file : '{}' {} ", path.toUri(),
humanReadableByteCount(fileSystem.getFileStatus(path).getLen(), false));
try (FSDataInputStream fsIs = fileSystem.open(path)) {
BufferedReader br;
br = new BufferedReader(new InputStreamReader(fsIs));
InputStream is;
if (removeExtraHeaders && i != 0) {
String line;
do {
br.mark(10 * 1024 * 1024); //10MB
line = br.readLine();
} while (line != null && line.startsWith("
br.reset();
is = new ReaderInputStream(br, Charset.defaultCharset());
} else {
is = fsIs;
}
IOUtils.copyBytes(is, os, getConf(), false);
}
}
}
LOGGER.info("File size : " + humanReadableByteCount(Files.size(Paths.get(localOutput.toUri())), false));
}
return paths;
}
protected final int getServersSize(String table) throws IOException {
int serversSize;
try (HBaseManager hBaseManager = new HBaseManager(getConf())) {
serversSize = hBaseManager.act(table, (t, admin) -> admin.getClusterStatus().getServersSize());
}
return serversSize;
}
public static String[] buildArgs(String table, ObjectMap options) {
List<String> args = new ArrayList<>(1 + options.size() * 2);
args.add(table);
addMap(args, options, "");
return args.toArray(new String[0]);
}
private static void addMap(List<String> args, ObjectMap options, String keyPrefix) {
for (String key : options.keySet()) {
if (options.get(key) instanceof Map) {
ObjectMap map = new ObjectMap(options.getMap(key));
addMap(args, map, keyPrefix + key + ".");
} else {
String value = options.getString(key);
if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
String finalKey = keyPrefix + key;
if (finalKey.equals(MR_EXECUTOR_SSH_PASSWORD.key())) {
continue;
}
args.add(finalKey);
args.add(value);
}
}
}
}
protected static void main(String[] args, Class<? extends Tool> aClass) {
try {
Tool tool = aClass.newInstance();
int code = ToolRunner.run(tool, args);
System.exit(code);
} catch (Exception e) {
LoggerFactory.getLogger(aClass).error("Error executing " + aClass, e);
System.exit(1);
}
}
public int privateMain(String[] args) throws Exception {
return privateMain(args, getConf());
}
public int privateMain(String[] args, Configuration conf) throws Exception {
if (conf != null) {
setConf(conf);
}
return ToolRunner.run(this, args);
}
}
|
package com.redhat.ceylon.eclipse.code.quickfix;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CORRECTION;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getUnits;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.text.edits.InsertEdit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.eclipse.code.editor.Util;
import com.redhat.ceylon.eclipse.code.search.FindContainerVisitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
public class AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable extends ChangeCorrectionProposal {
public static void addConstraintSatisfiesProposals(Tree.CompilationUnit cu, Node node, Collection<ICompletionProposal> proposals, IProject project) {
TypeParameter typeParam = determineTypeParam(node);
if( typeParam == null ) {
return;
}
Tree.ClassOrInterface typeParamContainer = determineTypeParamContainer(cu, node);
if (!(typeParamContainer instanceof Tree.ClassDefinition) && !(typeParamContainer instanceof Tree.InterfaceDefinition)) {
return;
}
List<TypeParameter> stTypeParams = determineSatisfiedTypesTypeParams(typeParam, typeParamContainer);
if (stTypeParams.isEmpty()) {
return;
}
List<ProducedType> missingSatisfiedTypes = determineMissingSatisfiedTypes(typeParam, stTypeParams);
if( missingSatisfiedTypes.isEmpty() ) {
return;
}
String changeText = createMissingSatisfiedTypesText(typeParam, stTypeParams, missingSatisfiedTypes);
TextFileChange change = createMissingSatisfiedTypesChange(typeParam, typeParamContainer, changeText, project);
AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable p = new AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable(typeParam, changeText, change);
if ( !proposals.contains(p)) {
proposals.add(p);
}
}
private static TypeParameter determineTypeParam(Node node) {
TypeParameter typeParameter = null;
if (node instanceof Tree.BaseType) {
TypeDeclaration baseTypeDecl = ((Tree.BaseType) node).getDeclarationModel();
if (baseTypeDecl instanceof TypeParameter) {
typeParameter = (TypeParameter) baseTypeDecl;
}
}
if (node instanceof Tree.TypeParameterDeclaration) {
typeParameter = ((Tree.TypeParameterDeclaration) node).getDeclarationModel();
}
return typeParameter;
}
private static Tree.ClassOrInterface determineTypeParamContainer(Tree.CompilationUnit cu, Node typeParamNode) {
FindContainerVisitor fcv = new FindContainerVisitor(typeParamNode);
fcv.visit(cu);
if (fcv.getStatementOrArgument() instanceof Tree.ClassOrInterface) {
return (Tree.ClassOrInterface) fcv.getStatementOrArgument();
}
return null;
}
private static List<TypeParameter> determineSatisfiedTypesTypeParams(TypeParameter typeParam, Tree.ClassOrInterface typeParamContainer) {
List<TypeParameter> stTypeParams = new ArrayList<TypeParameter>();
if( typeParamContainer.getSatisfiedTypes() != null ) {
for( Tree.SimpleType st : typeParamContainer.getSatisfiedTypes().getTypes() ) {
if( st.getTypeArgumentList() != null ) {
List<Tree.Type> stTypeArguments = st.getTypeArgumentList().getTypes();
for (int i = 0; i < stTypeArguments.size(); i++) {
Tree.SimpleType stTypeArgument = (Tree.SimpleType)stTypeArguments.get(i);
if (typeParam.getName().equals(
stTypeArgument.getDeclarationModel().getName())) {
TypeDeclaration stDecl = st.getDeclarationModel();
if( stDecl != null ) {
if( stDecl.getTypeParameters() != null && stDecl.getTypeParameters().size() > i ) {
stTypeParams.add(stDecl.getTypeParameters().get(i));
}
}
}
}
}
}
}
return stTypeParams;
}
private static List<ProducedType> determineMissingSatisfiedTypes(TypeParameter typeParam, List<TypeParameter> stTypeParams) {
ProducedType typeParamType = typeParam.getType();
Map<TypeParameter, ProducedType> substitutions = new HashMap<>();
for (TypeParameter stTypeParam : stTypeParams) {
substitutions.put(stTypeParam, typeParamType);
}
List<ProducedType> missingSatisfiedTypes = new ArrayList<ProducedType>();
for(TypeParameter stTypeParam : stTypeParams) {
for(ProducedType stTypeParamSatisfiedType : stTypeParam.getSatisfiedTypes()) {
stTypeParamSatisfiedType = stTypeParamSatisfiedType.substitute(substitutions);
boolean isMissing = true;
for (ProducedType typeParamSatisfiedType : typeParam.getSatisfiedTypes()) {
if (stTypeParamSatisfiedType.isSupertypeOf(typeParamSatisfiedType)) {
isMissing = false;
break;
}
}
if( isMissing ) {
for(ProducedType missingSatisfiedType : missingSatisfiedTypes) {
if( missingSatisfiedType.isExactly(stTypeParamSatisfiedType) ) {
isMissing = false;
break;
}
}
}
if( isMissing ) {
missingSatisfiedTypes.add(stTypeParamSatisfiedType);
}
}
}
return missingSatisfiedTypes;
}
private static String createMissingSatisfiedTypesText(TypeParameter typeParam, List<TypeParameter> stTypeParams, List<ProducedType> missingSatisfiedTypes) {
StringBuffer missingSatisfiedTypesText = new StringBuffer();
for( ProducedType missingSatisfiedType : missingSatisfiedTypes ) {
if( missingSatisfiedTypesText.length() != 0 ) {
missingSatisfiedTypesText.append(" & ");
}
missingSatisfiedTypesText.append(missingSatisfiedType.getProducedTypeName());
}
return missingSatisfiedTypesText.toString();
}
private static TextFileChange createMissingSatisfiedTypesChange(TypeParameter typeParam, Tree.ClassOrInterface typeParamContainer, String missingSatisfiedTypesText, IProject project) {
String changeText = null;
Integer changeIndex = null;
if( typeParamContainer.getTypeConstraintList() != null ) {
for( Tree.TypeConstraint typeConstraint : typeParamContainer.getTypeConstraintList().getTypeConstraints() ) {
if( typeConstraint.getDeclarationModel().equals(typeParam) ) {
changeText = " & " + missingSatisfiedTypesText;
changeIndex = typeConstraint.getStopIndex() + 1;
break;
}
}
}
if( changeText == null ) {
changeText = "given "+ typeParam.getName() + " satisfies " + missingSatisfiedTypesText + " ";
if( typeParamContainer instanceof Tree.ClassDefinition ) {
changeIndex = ((Tree.ClassDefinition)typeParamContainer).getClassBody().getStartIndex();
}
if( typeParamContainer instanceof Tree.InterfaceDefinition ) {
changeIndex = ((Tree.InterfaceDefinition)typeParamContainer).getInterfaceBody().getStartIndex();
}
}
for (PhasedUnit unit: getUnits(project)) {
if (typeParam.getUnit().equals(unit.getUnit())) {
if( changeText != null ) {
IFile file = CeylonBuilder.getFile(unit);
TextFileChange change = new TextFileChange("Add generic type constraints", file);
change.setEdit(new InsertEdit(changeIndex, changeText));
return change;
}
break;
}
}
return null;
}
private TextFileChange change;
private TypeParameter typeParam;
private String missingSatisfiedTypeText;
private AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable(TypeParameter typeParam, String missingSatisfiedTypeText, TextFileChange change) {
super("Add generic type constraints '" + typeParam.getName() + " satisfies " + missingSatisfiedTypeText + "'", change, 10, CORRECTION);
this.change = change;
this.typeParam = typeParam;
this.missingSatisfiedTypeText = missingSatisfiedTypeText;
}
@Override
public void apply(IDocument document) {
super.apply(document);
Util.gotoLocation(change.getFile(), change.getEdit().getOffset());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable) {
AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable that = (AddConstraintSatisfiesProposalOnTypeArgumentIsNotAssignable) obj;
return that.typeParam.equals(typeParam) && that.missingSatisfiedTypeText.equals(missingSatisfiedTypeText);
}
return false;
}
@Override
public int hashCode() {
return typeParam.hashCode() + missingSatisfiedTypeText.hashCode();
}
}
|
package hu.elte.txtuml.export.papyrus.elementsarrangers.txtumllayout;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.uml2.uml.Element;
import hu.elte.txtuml.export.papyrus.api.DiagramElementsModifier;
import hu.elte.txtuml.export.papyrus.elementsarrangers.AbstractDiagramElementsArranger;
import hu.elte.txtuml.export.papyrus.elementsarrangers.ArrangeException;
import hu.elte.txtuml.export.papyrus.elementsarrangers.txtumllayout.LayoutTransformer.OrigoConstraint;
import hu.elte.txtuml.export.papyrus.layout.txtuml.TxtUMLElementsRegistry;
import hu.elte.txtuml.layout.export.DiagramExportationReport;
import hu.elte.txtuml.layout.visualizer.model.AssociationType;
import hu.elte.txtuml.layout.visualizer.model.LineAssociation;
import hu.elte.txtuml.layout.visualizer.model.RectangleObject;
import hu.elte.txtuml.layout.visualizer.statements.Statement;
import hu.elte.txtuml.layout.visualizer.statements.StatementType;
public abstract class AbstractDiagramElementsTxtUmlArranger extends AbstractDiagramElementsArranger{
private TxtUMLElementsRegistry txtUmlRegistry;
/**
* The Constructor
* @param diagramEditPart - The EditPart of the diagram which elements is to arranged.
* @param txtUmlRegistry - The {@link TxtUMLElementsRegistry} which specifies the layout
*/
public AbstractDiagramElementsTxtUmlArranger(DiagramEditPart diagramEditPart, TxtUMLElementsRegistry txtUmlRegistry) {
super(diagramEditPart);
this.txtUmlRegistry = txtUmlRegistry;
}
/**
* Arranges the children of an EditPart with the txtUML arranging algorithm
* @param parent - The children of this EditPart will be arranged
* @throws ArrangeException
*/
protected void arrangeChildren(EditPart parent, IProgressMonitor monitor) throws ArrangeException{
@SuppressWarnings("unchecked")
List<EditPart> editParts = parent.getChildren();
if(!editParts.isEmpty()){
int MAXPIXELWIDTH = 200;
int MAXPIXELHEIGHT = 200;
DiagramExportationReport report = txtUmlRegistry.getDescriptor().getReport(this.diagep.getDiagramView().getName());
Set<RectangleObject> objects = report.getNodes();
Set<LineAssociation> links = report.getLinks();
List<Statement> statements = report.getStatements();
statements.add(new Statement(StatementType.corridorsize, "0.5"));
Map<GraphicalEditPart, RectangleObject> editPartsObjectsMapping = pairObjectsToEditParts(objects, editParts);
setPixelsizes(editPartsObjectsMapping, MAXPIXELWIDTH, MAXPIXELHEIGHT);
LayoutVisualizerManager vm = new LayoutVisualizerManager(objects, links, statements);
vm.addProgressMonitor(monitor);
vm.arrange();
objects = vm.getObjects();
links = vm.getAssociations();
List<ConnectionNodeEditPart> connections = getConnectionsOfEditParts(editParts);
Map<ConnectionNodeEditPart, List<Point>> linksTransform = pairRoutesToConnectionEditParts(links, connections);
Map<GraphicalEditPart, Rectangle> objectsTransform = createObjectRectangleMappingFromObjectsAndEditParts(objects, editParts);
int pixelGridRatio = vm.getPixelGridRatio();
transformObjectsAndLinks(objectsTransform, linksTransform, pixelGridRatio);
modifyEditParts(objectsTransform);
modifyConnectionEditParts(linksTransform, objectsTransform);
}
}
private Map<GraphicalEditPart, Rectangle> createObjectRectangleMappingFromObjectsAndEditParts(Set<RectangleObject> objects,
List<EditPart> editParts) {
Map<GraphicalEditPart, Rectangle> result = new HashMap<>();
for(RectangleObject obj : objects){
Optional<Element> e = txtUmlRegistry.findElement(obj.getName());
if(e.isPresent()){
GraphicalEditPart ep = (GraphicalEditPart) getEditPartOfModelElement(editParts, e.get());
if(ep != null){
Rectangle rect = new Rectangle(obj.getPosition().getX(), obj.getPosition().getY(),
obj.getPixelWidth(), obj.getPixelHeight());
result.put(ep, rect);
}
}
}
return result;
}
private void setPixelsizes(Map<GraphicalEditPart, RectangleObject> editPartsObjectsMapping, int maxW, int maxH) {
editPartsObjectsMapping.forEach((GraphicalEditPart ep, RectangleObject obj) -> {
int w = getSize(ep).width;
int h = getSize(ep).height;
obj.setPixelWidth(w > maxW ? maxW : w);
obj.setPixelHeight(h > maxH ? maxH : h);
});
}
private void modifyConnectionEditParts(
Map<ConnectionNodeEditPart, List<Point>> linksTransform,
Map<GraphicalEditPart, Rectangle> objectTransform) {
linksTransform.forEach((ConnectionNodeEditPart connection, List<Point> route) ->{
if(connection != null && route.size() >= 2){
Rectangle source = objectTransform.get(connection.getSource());
Rectangle target = objectTransform.get(connection.getTarget());
String anchor_start = getAnchor(source.getTopLeft(), route.get(0), source.width, source.height);
String anchor_end = getAnchor(target.getTopLeft(), route.get(route.size()-1), target.width, target.height);
route.remove(0);
route.remove(route.size()-1);
connection.getSource();
DiagramElementsModifier.setConnectionAnchors(connection, anchor_start, anchor_end);
DiagramElementsModifier.setConnectionBendpoints(connection, route);
}
});
}
private void modifyEditParts(
Map<GraphicalEditPart, Rectangle> editPartsObjectsMapping) {
editPartsObjectsMapping.forEach((GraphicalEditPart ep, Rectangle rect) -> {
DiagramElementsModifier.resizeGraphicalEditPart(ep, rect.width, rect.height);
DiagramElementsModifier.moveGraphicalEditPart(ep, rect.getTopLeft());
});
}
private void transformObjectsAndLinks(
Map<GraphicalEditPart, Rectangle> objectsTransform,
Map<ConnectionNodeEditPart, List<Point>> linksTransform, int pixelGridRatio) {
LayoutTransformer trans = new LayoutTransformer(pixelGridRatio);
trans.setOrigo(OrigoConstraint.UpperLeft);
trans.flipYAxis();
trans.doTranformations(objectsTransform, linksTransform);
}
private Map<ConnectionNodeEditPart, List<Point>> pairRoutesToConnectionEditParts(
Collection<LineAssociation> links,
List<ConnectionNodeEditPart> connections) {
Map<ConnectionNodeEditPart, List<Point>> linksTransform = new HashMap<ConnectionNodeEditPart, List<Point>>();
for(LineAssociation la : links){
Optional<? extends Element> e = txtUmlRegistry.findAssociation(la.getId());
if(!e.isPresent()) e = txtUmlRegistry.findGeneralization(la.getFrom(), la.getTo());
if(e.isPresent()){
ConnectionNodeEditPart connection = (ConnectionNodeEditPart) getEditPartOfModelElement(connections, e.get());
Element source = (Element) ((View)connection.getSource().getModel()).getElement();
Element target = (Element) ((View)connection.getTarget().getModel()).getElement();
Optional<Element> from = txtUmlRegistry.findElement(la.getFrom());
Optional<Element> to = txtUmlRegistry.findElement(la.getTo());
if(!from.isPresent() || !to.isPresent()) continue;
List<Point> route = new LinkedList<Point>();
List<hu.elte.txtuml.layout.visualizer.model.Point> layoutRoute = la.getMinimalRoute();
for(int i = 0; i < layoutRoute.size(); i++){
int index = i;
/*
* if the type is a generalization or the source-end relation is different
* in the two representation, the order of the route points should be reversed
*/
if(la.getType() == AssociationType.generalization || (from.get() == target && to.get() == source)){
index = layoutRoute.size()-i-1;
}
route.add(new Point(layoutRoute.get(index).getX(),layoutRoute.get(index).getY()));
}
linksTransform.put(connection, route);
}
}
return linksTransform;
}
private Map<GraphicalEditPart, RectangleObject> pairObjectsToEditParts(Collection<RectangleObject> objects,
List<EditPart> editParts) {
Map<GraphicalEditPart, RectangleObject> objectsTransform = new HashMap<>();
for(RectangleObject obj : objects){
Optional<Element> e = txtUmlRegistry.findElement(obj.getName());
if(e.isPresent()){
GraphicalEditPart ep = (GraphicalEditPart) getEditPartOfModelElement(editParts, e.get());
if(ep != null){
objectsTransform.put(ep, obj);
}
}
}
return objectsTransform;
}
private List<ConnectionNodeEditPart> getConnectionsOfEditParts(List<EditPart> editParts) {
List<ConnectionNodeEditPart> connections = new LinkedList<ConnectionNodeEditPart>();
for (EditPart editpart : editParts) {
@SuppressWarnings("unchecked")
List<ConnectionNodeEditPart> conns = ((GraphicalEditPart) editpart).getSourceConnections();
connections.addAll(conns);
}
return connections;
}
/**
* @param center
* @param edge
* @return
*/
protected String getAnchor(Point topleft, Point edge, int objectWidth, int objectHeight){
Point relativeEdge = edge.getTranslated(topleft.getNegated());
double anchor_x = ((float) relativeEdge.x())/((float) objectWidth);
double anchor_y = ((float) relativeEdge.y())/((float) objectHeight);
return new String("("+anchor_x+", "+anchor_y+")");
}
/**
* Gets the size of a GrapchicalEditPart
* @param editpart - The GraphicalEditPart
* @return The size
*/
protected Dimension getSize(GraphicalEditPart editpart){
return editpart.getFigure().getPreferredSize();
}
/* TODO Maybe this function could have been also used somewhere else - Future refactor needed */
private EditPart getEditPartOfModelElement(Collection<? extends EditPart> editParts, Element element) {
if(element == null) return null;
for (EditPart ep : editParts) {
Element actual = (Element) ((View) ep.getModel()).getElement();
if(actual.equals(element))
return ep;
}
return null;
}
}
|
package org.xwiki.workspace.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import com.xpn.xwiki.XWikiException;
import org.slf4j.Logger;
import org.xwiki.bridge.event.WikiDeletedEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.context.Execution;
import org.xwiki.localization.ContextualLocalizationManager;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.observation.ObservationManager;
import org.xwiki.script.service.ScriptService;
import org.xwiki.security.authorization.AuthorizationManager;
import org.xwiki.workspace.Workspace;
import org.xwiki.workspace.WorkspaceException;
import org.xwiki.workspace.WorkspaceManager;
import org.xwiki.workspace.WorkspaceManagerMessageTool;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseElement;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.PropertyInterface;
import com.xpn.xwiki.plugin.wikimanager.WikiManager;
import com.xpn.xwiki.plugin.wikimanager.doc.Wiki;
import com.xpn.xwiki.plugin.wikimanager.doc.XWikiServer;
import com.xpn.xwiki.plugin.wikimanager.internal.WikiManagerScriptService;
import com.xpn.xwiki.user.api.XWikiRightService;
/**
* Implementation of a <tt>WorkspaceManager</tt> component.
*
* @version $Id$
*/
@Component
public class DefaultWorkspaceManager implements WorkspaceManager, Initializable
{
/** Member property of the group class. */
private static final String GROUP_CLASS_MEMBER_PROPERTY = "member";
/** Default XWiki space used to store wiki descriptors. */
private static final String XWIKI_SPACE = "XWiki";
/** Workspace Class used to mark and extend a wiki descriptor. */
private static final String WORKSPACE_CLASS = "WorkspaceClass";
/** Workspace Manager application space. */
private static final String WORKSPACE_MANAGER_SPACE = "WorkspaceManager";
/** Admin right. */
private static final String RIGHT_ADMIN = "admin";
/** Wiki preferences page for local wiki (unprefixed and relative to the current wiki). */
private static final String WIKI_PREFERENCES_LOCAL = "XWiki.XWikiPreferences";
/** Format string for the wiki preferences page of a certain wiki (absolute reference). */
private static final String WIKI_PREFERENCES_PREFIXED_FORMAT = "%s:" + WIKI_PREFERENCES_LOCAL;
/** Membership type property name. */
private static final String WORKSPACE_MEMBERSHIP_TYPE_PROPERTY = "membershipType";
/** Membership type default value. */
private static final String WORKSPACE_MEMBERSHIP_TYPE_DEFAULT = "open";
/** Logging tool. */
@Inject
private static Logger logger;
/** Execution context. */
@Inject
private Execution execution;
/** Observation manager needed to fire events. */
@Inject
private ObservationManager observationManager;
/**
* Wiki Manager Script service that we are using instead of the deprecated PluginAPI, until a decent WikiManager
* component becomes available.
*/
@Inject
@Named("wikimanager")
private ScriptService wikiManagerService;
/**
* Used to access translations.
*/
@Inject
private ContextualLocalizationManager localizationManager;
/** Internal wiki manager tookit required to overcome the rights checking of the API. */
private WikiManager wikiManagerInternal;
@Override
public void initialize() throws InitializationException
{
this.wikiManagerInternal = new WikiManager();
}
/**
* Convenience method to avoid writing the cast every time.
*
* @return the wiki manager script service implementation that exposes the API.
*/
private WikiManagerScriptService getWikiManager()
{
WikiManagerScriptService scriptService = (WikiManagerScriptService) wikiManagerService;
return scriptService;
}
@Override
public boolean canCreateWorkspace(String userName, String workspaceName)
{
/* User name input validation. */
if (userName == null || userName.trim().length() == 0) {
return false;
}
/* Check if the user has the SUBWIKI_CREATION right */
try{
XWikiContext deprecatedContext = getXWikiContext();
XWikiRightService rightService = deprecatedContext.getWiki().getRightService();
String mainWikiPreferencesDocumentName =
String.format(WIKI_PREFERENCES_PREFIXED_FORMAT, deprecatedContext.getMainXWiki());
if(!rightService.hasAccessLevel("subwikicreation", userName, mainWikiPreferencesDocumentName,
deprecatedContext)){
return false;
}
}catch(XWikiException e){
if (logger.isErrorEnabled()) {
logger.error("Failed to check if user [{}] can create a workspace. Assuming false.", new Object[] {
userName, e});
}
return false;
}
/* Check if it already exists. */
if (isWorkspace(workspaceName)) {
return false;
}
return true;
}
@Override
public boolean canEditWorkspace(String userName, String workspaceName)
{
if (!isWorkspace(workspaceName)) {
return false;
}
XWikiContext deprecatedContext = getXWikiContext();
try {
XWikiServer wikiServer = getWikiManager().getWikiDocument(workspaceName);
String wikiOwner = wikiServer.getOwner();
XWikiRightService rightService = deprecatedContext.getWiki().getRightService();
String mainWikiPreferencesDocumentName =
String.format(WIKI_PREFERENCES_PREFIXED_FORMAT, deprecatedContext.getMainXWiki());
/* Owner or main wiki admin. */
return wikiOwner.equals(userName)
|| rightService.hasAccessLevel(RIGHT_ADMIN, userName, mainWikiPreferencesDocumentName,
deprecatedContext);
} catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error("Failed to check if user [{}] can edit workspace [{}]. Assuming false.", new Object[] {
userName, workspaceName, e});
}
return false;
}
}
@Override
public boolean canDeleteWorkspace(String userName, String workspaceName)
{
if (!isWorkspace(workspaceName)) {
return false;
}
XWikiContext deprecatedContext = getXWikiContext();
try {
XWikiServer wikiServer = getWikiManager().getWikiDocument(workspaceName);
String wikiOwner = wikiServer.getOwner();
XWikiRightService rightService = deprecatedContext.getWiki().getRightService();
String mainWikiPreferencesDocumentName =
String.format(WIKI_PREFERENCES_PREFIXED_FORMAT, deprecatedContext.getMainXWiki());
/* Owner or main wiki admin. */
return (wikiOwner.equals(userName) || rightService.hasAccessLevel(RIGHT_ADMIN, userName,
mainWikiPreferencesDocumentName, deprecatedContext));
} catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error("Failed to check if user [{}] can delete workspace [{}]. Assuming false.", new Object[] {
userName, workspaceName, e});
}
return false;
}
}
/**
* @return the deprecated xwiki context used to manipulate xwiki objects
*/
private XWikiContext getXWikiContext()
{
return (XWikiContext) execution.getContext().getProperty("xwikicontext");
}
@Override
public XWikiServer createWorkspace(XWikiServer newWikiXObjectDocument) throws WorkspaceException
{
return this.createWorkspace(newWikiXObjectDocument, "workspacetemplate");
}
@Override
public XWikiServer createWorkspace(XWikiServer newWikiXObjectDocument, String templateWikiName)
throws WorkspaceException
{
XWikiContext deprecatedContext = getXWikiContext();
String workspaceName = newWikiXObjectDocument.getWikiName();
String comment = String.format("Created new workspace '%s'", workspaceName);
/* Create new wiki. */
XWikiServer result = null;
try {
result =
this.wikiManagerInternal.createNewWikiFromTemplate(newWikiXObjectDocument, templateWikiName, true,
comment, deprecatedContext);
} catch (Exception e) {
logAndThrowException(String.format("Failed to create workspace [%s]", workspaceName), e);
}
/*
* Use the XWiki.XWikiAllGroup of the new wiki to add the owner as a member and the XWiki.XWikiAdminGroup of the
* new wiki to explicitly add the owner as an admin.
*/
String workspaceOwner = newWikiXObjectDocument.getOwner();
try {
initializeOwner(workspaceName, workspaceOwner, comment);
} catch (Exception e) {
logger.error("Failed to add owner to workspace group for workspace [{}].", workspaceName, e);
}
/* Add workspace marker object. */
XWikiDocument wikiDocument = newWikiXObjectDocument.getDocument();
try {
initializeMarker(wikiDocument, comment);
} catch (Exception e) {
logger.error("Failed to add workspace marker for workspace [{}].", workspaceName, e);
}
/* TODO: Launch workspace created event. */
return result;
}
/**
* Initialize a newly created workspace by explicitly adding its owner in the XWikiAllGroup and XWikiAdminGroup
* local groups, only if he's not already a member.
*
* @param workspaceName the workspace to initialize
* @param workspaceOwner the owner user name to be used in the process
* @param comment the comment used when saving the group documents
* @throws Exception if problems occur
*/
private void initializeOwner(String workspaceName, String workspaceOwner, String comment) throws Exception
{
/* Add user as workspace member. */
DocumentReference workspaceGroupReference =
new DocumentReference(workspaceName, Workspace.WORKSPACE_GROUP_SPACE, Workspace.WORKSPACE_GROUP_PAGE);
addUserToGroupIfNotAlreadyMember(workspaceOwner, workspaceGroupReference, comment);
/* Add user as workspace admin. */
DocumentReference workspaceAdminGroupReference =
new DocumentReference(workspaceName, XWIKI_SPACE, "XWikiAdminGroup");
addUserToGroupIfNotAlreadyMember(workspaceOwner, workspaceAdminGroupReference, comment);
}
/**
* Adds a user to a group if the user is not already a member.
*
* @param userStringReference serialized reference of the user to add
* @param workspaceGroupReference the group document where to add the user
* @param comment optional comment used when saving the group documents
* @throws Exception if problems occur
*/
private void addUserToGroupIfNotAlreadyMember(String userStringReference,
DocumentReference workspaceGroupReference, String comment) throws Exception
{
XWikiContext deprecatedContext = getXWikiContext();
XWiki xwiki = deprecatedContext.getWiki();
String currentWikiName = deprecatedContext.getDatabase();
try {
deprecatedContext.setDatabase(workspaceGroupReference.getWikiReference().getName());
DocumentReference groupClassReference = xwiki.getGroupClass(deprecatedContext).getDocumentReference();
XWikiDocument workspaceGroupDocument = xwiki.getDocument(workspaceGroupReference, deprecatedContext);
BaseObject workspaceGroupObject =
workspaceGroupDocument
.getXObject(groupClassReference, GROUP_CLASS_MEMBER_PROPERTY, userStringReference);
if (workspaceGroupObject == null) {
workspaceGroupObject = workspaceGroupDocument.newXObject(groupClassReference, deprecatedContext);
workspaceGroupObject.setStringValue(GROUP_CLASS_MEMBER_PROPERTY, userStringReference);
xwiki.saveDocument(workspaceGroupDocument, comment, deprecatedContext);
}
// FIXME: See if we need to update the group service cache.
// try {
// XWikiGroupService gservice = getGroupService(context);
// gservice.addUserToGroup(userName, context.getDatabase(), groupName, context);
// } catch (Exception e) {
// LOG.error("Failed to update group service cache", e);
} finally {
deprecatedContext.setDatabase(currentWikiName);
}
}
/**
* @param wikiDocument the wiki descriptor document to initialize
* @param comment the comment used when saving the wiki descriptor document
* @throws Exception if problems occur
*/
private void initializeMarker(XWikiDocument wikiDocument, String comment) throws Exception
{
XWikiContext deprecatedContext = getXWikiContext();
String mainWikiName = deprecatedContext.getMainXWiki();
DocumentReference workspaceClassReference =
new DocumentReference(mainWikiName, WORKSPACE_MANAGER_SPACE, WORKSPACE_CLASS);
BaseObject workspaceObject = wikiDocument.getXObject(workspaceClassReference);
if (workspaceObject == null) {
workspaceObject = wikiDocument.newXObject(workspaceClassReference, deprecatedContext);
}
/* Make sure the required workspace attributes are set. */
if (workspaceObject.getStringValue(WORKSPACE_MEMBERSHIP_TYPE_PROPERTY) == null) {
workspaceObject.setStringValue(WORKSPACE_MEMBERSHIP_TYPE_PROPERTY, WORKSPACE_MEMBERSHIP_TYPE_DEFAULT);
}
deprecatedContext.getWiki().saveDocument(wikiDocument, comment, deprecatedContext);
}
@Override
public void deleteWorkspace(String workspaceName) throws WorkspaceException
{
Workspace workspace = getWorkspace(workspaceName);
if (workspace == null) {
throw new WorkspaceException(String.format("Workspace '%s' does not exist", workspaceName));
}
XWikiContext deprecatedContext = getXWikiContext();
XWiki xwiki = deprecatedContext.getWiki();
/*
* Copy/paste from Wiki.delete(boolean deleteDatabase) because it checks internally for admin rights and the
* current user, even if he is the owner of a wiki, might not have admin rights to the main wiki. If the method
* is called from the main wiki, an owner might not be allowed to delete his wiki. This way we fix it.
*/
try {
xwiki.getStore().deleteWiki(workspaceName, deprecatedContext);
observationManager.notify(new WikiDeletedEvent(workspaceName), workspaceName, deprecatedContext);
} catch (Exception e) {
throw new WorkspaceException(String.format("Failed to delete wiki '%s' from database", workspaceName), e);
}
try {
xwiki.deleteDocument(workspace.getWikiDescriptor().getDocument(), false, deprecatedContext);
} catch (Exception e) {
throw new WorkspaceException(
String.format("Failed to delete wiki descriptor for workspace '%s'", workspace), e);
}
}
@Override
public void editWorkspace(String workspaceName, XWikiServer modifiedWikiXObjectDocument) throws WorkspaceException
{
Workspace workspace = getWorkspace(workspaceName);
XWikiContext deprecatedContext = getXWikiContext();
XWiki xwiki = deprecatedContext.getWiki();
Wiki wikiDocument = workspace.getWikiDocument();
XWikiDocument coreWikiDocument = wikiDocument.getDocument();
/*
* Handle changes in the wiki descriptor.
*/
DocumentReference xwikiServerClassReference =
new DocumentReference(deprecatedContext.getMainXWiki(), XWIKI_SPACE, "XWikiServerClass");
BaseObject currentWikiObject = coreWikiDocument.getXObject(xwikiServerClassReference);
BaseObject modifiedWikiObject = modifiedWikiXObjectDocument.getDocument().getXObject(xwikiServerClassReference);
/* Merge the two. */
updateObject(modifiedWikiObject, currentWikiObject);
/*
* Handle changes in the workspace descriptor.
*/
DocumentReference workspaceClassReference =
new DocumentReference(deprecatedContext.getMainXWiki(), WORKSPACE_MANAGER_SPACE, WORKSPACE_CLASS);
BaseObject currentWorkspaceObject = coreWikiDocument.getXObject(workspaceClassReference);
BaseObject modifiedWorkspaceObject =
modifiedWikiXObjectDocument.getDocument().getXObject(workspaceClassReference);
/* Merge the two. */
updateObject(modifiedWorkspaceObject, currentWorkspaceObject);
/*
* Save the changes.
*/
try {
xwiki.saveDocument(coreWikiDocument, "Workspace edited", true, deprecatedContext);
} catch (Exception e) {
throw new WorkspaceException("Failed to save modifications.", e);
}
// Re-initialize the owner of the workspace, since it could have changed
try {
this.initializeOwner(workspaceName, modifiedWikiXObjectDocument.getOwner(), "New owner");
} catch (Exception e) {
throw new WorkspaceException("Failed to add the new owner to the workspace all and admin groups.", e);
}
}
/**
* Update the contents of an object using the contents of another. Objects must be of the same class.
*
* @param source object that provides the new contents to update with
* @param destination object that is to be updated
* @throws WorkspaceException if objects' classes differ
*/
private void updateObject(BaseObject source, BaseObject destination) throws WorkspaceException
{
if (!source.getXClassReference().equals(destination.getXClassReference())) {
throw new WorkspaceException(String.format("Objects classes are not equal: %s vs %s", source
.getXClassReference().toString(), destination.getXClassReference().toString()));
}
Iterator<String> itfields = source.getPropertyList().iterator();
while (itfields.hasNext()) {
String name = itfields.next();
destination.safeput(name, (PropertyInterface) ((BaseElement) source.safeget(name)).clone());
}
}
@Override
public Workspace getWorkspace(String workspaceName) throws WorkspaceException
{
XWikiContext deprecatedContext = getXWikiContext();
XWiki xwiki = deprecatedContext.getWiki();
/* Main wiki can not be a workspace. */
if (deprecatedContext.getMainXWiki().equals(workspaceName)) {
return null;
}
Workspace result = null;
try {
Wiki wikiDocument = getWikiManager().getWikiFromName(workspaceName);
if (wikiDocument == null || wikiDocument.isNew()) {
return null;
}
XWikiServer wikiDescriptor = wikiDocument.getFirstWikiAlias();
if (wikiDescriptor == null || wikiDescriptor.isNew()) {
throw new WorkspaceException(this.localizationManager.getTranslationPlain(
WorkspaceManagerMessageTool.ERROR_WORKSPACEINVALID, Arrays.asList(workspaceName)));
}
BaseObject workspaceObject = getWorkspaceObject(wikiDocument);
if (workspaceObject == null) {
return null;
}
DocumentReference groupReference =
new DocumentReference(workspaceName, Workspace.WORKSPACE_GROUP_SPACE, Workspace.WORKSPACE_GROUP_PAGE);
if (!xwiki.exists(groupReference, deprecatedContext)) {
throw new WorkspaceException(this.localizationManager.getTranslationPlain(
WorkspaceManagerMessageTool.ERROR_WORKSPACEINVALID, Arrays.asList(workspaceName)));
}
result =
new DefaultWorkspace(wikiDocument, wikiDescriptor, new Document(xwiki.getDocument(groupReference,
deprecatedContext), deprecatedContext));
} catch (Exception e) {
logAndThrowException(this.localizationManager.getTranslationPlain(
WorkspaceManagerMessageTool.ERROR_WORKSPACEGET,
Arrays.asList(workspaceName, e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())),
e);
}
return result;
}
@Override
public List<Workspace> getWorkspaces() throws WorkspaceException
{
List<Workspace> result = new ArrayList<Workspace>();
try {
List<Wiki> wikis = getWikiManager().getAllWikis();
for (Wiki wiki : wikis) {
try {
BaseObject workspaceObject = getWorkspaceObject(wiki);
if (workspaceObject != null) {
Workspace workspace = getWorkspace(wiki.getWikiName());
result.add(workspace);
}
} catch (Exception e) {
/* Log and skip. */
logger.warn(this.localizationManager.getTranslationPlain(
WorkspaceManagerMessageTool.LOG_WORKSPACEINVALID, Arrays.asList(wiki.getWikiName())), e);
continue;
}
}
} catch (Exception e) {
logAndThrowException(
this.localizationManager.getTranslationPlain(WorkspaceManagerMessageTool.ERROR_WORKSPACEGETALL), e);
}
return result;
}
@Override
public List<Workspace> getWorkspaceTemplates() throws WorkspaceException
{
List<Workspace> result = new ArrayList<Workspace>();
List<Workspace> workspaces = getWorkspaces();
for (Workspace workspace : workspaces) {
XWikiServer server = workspace.getWikiDescriptor();
if (server.isWikiTemplate()) {
result.add(workspace);
}
}
return result;
}
/**
* @param wikiDocument the wiki descriptor document
* @return the WorkspaceClass object contained by the wiki document, if it is a workspace, <code>null</code>
* otherwise
* @throws Exception if problems occur
*/
private BaseObject getWorkspaceObject(Wiki wikiDocument) throws Exception
{
XWikiContext deprecatedContext = getXWikiContext();
XWiki xwiki = deprecatedContext.getWiki();
DocumentReference workspaceClassReference =
new DocumentReference(deprecatedContext.getMainXWiki(), WORKSPACE_MANAGER_SPACE, WORKSPACE_CLASS);
XWikiDocument xwikiCoreDocument = xwiki.getDocument(wikiDocument.getDocumentReference(), deprecatedContext);
BaseObject workspaceObject = xwikiCoreDocument.getXObject(workspaceClassReference);
return workspaceObject;
}
/**
* Utility method to log and throw a {@link WorkspaceException} wrapping a given exception.
*
* @param message the error message to log
* @param e the exception to log and wrap in the thrown {@link WorkspaceException}
* @throws WorkspaceException when called
*/
private void logAndThrowException(String message, Exception e) throws WorkspaceException
{
logger.error(message, e);
throw new WorkspaceException(message, e);
}
@Override
public boolean isWorkspace(String workspaceName)
{
try {
Workspace workspace = getWorkspace(workspaceName);
if (workspace != null) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
}
|
package activity;
import user.UserNameHandler;
import model.UserProfile;
import network_io.ProfileIoHandler;
import com.example.projectapp.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class ProfilePageActivity extends Activity {
private TextView profileTitle;
private ImageButton photo;
private EditText userNameInput;
private EditText biographyInput;
private EditText twitterInput;
private EditText facebookInput;
private ImageButton cancel;
private ImageButton commit;
private ProfileIoHandler profileIoHandler=null;
private UserNameHandler userNameHandler=null;
public static final int OBTAIN_PIC_REQUEST_CODE=252;
private Bitmap profilePhoto;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_page);
profileTitle=(TextView)findViewById(R.id.profile_title);
photo=(ImageButton)findViewById(R.id.profile_picture);
userNameInput=(EditText)findViewById(R.id.user_name);
biographyInput=(EditText)findViewById(R.id.biography);
twitterInput=(EditText)findViewById(R.id.twitter);
facebookInput=(EditText)findViewById(R.id.facebook);
cancel=(ImageButton)findViewById(R.id.cancel_profile);
commit=(ImageButton)findViewById(R.id.commit_profile);
profileIoHandler=new ProfileIoHandler();
userNameHandler=new UserNameHandler();
profileTitle.setText("User Profile: ");
profileIoHandler.loadSpecificProfileForUpdate(userNameHandler.getUserName(this),this, photo, userNameInput, biographyInput, twitterInput, facebookInput);
photo.setOnClickListener(new AttachPhotoClick());
cancel.setOnClickListener(new CancelClick());
commit.setOnClickListener(new UpdateProfileClick());
}
public void takeAPhoto(){
Intent camIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent,OBTAIN_PIC_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OBTAIN_PIC_REQUEST_CODE && resultCode == RESULT_OK) {
profilePhoto = (Bitmap)data.getExtras().get("data");
photo.setImageBitmap(profilePhoto);
}
}
class AttachPhotoClick implements OnClickListener{
@Override
public void onClick(View v){
takeAPhoto();
}
}
class UpdateProfileClick implements OnClickListener{
@Override
public void onClick(View v){
UserProfile newProfile=new UserProfile(userNameInput.getText().toString(),biographyInput.getText().toString(),
twitterInput.getText().toString(),facebookInput.getText().toString(),profilePhoto);
profileIoHandler.putOrUpdateProfile(newProfile);
finish();
}
}
class CancelClick implements OnClickListener{
@Override
public void onClick(View v){
finish();
}
}
}
|
package wge3.world;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.TimeUtils;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import wge3.entity.character.Bullet;
import wge3.entity.character.Creature;
import wge3.entity.character.NonPlayer;
import wge3.entity.character.Player;
import wge3.entity.mapobjects.LightSource;
import wge3.entity.terrainelements.Item;
import wge3.interfaces.Drawable;
public final class Area implements Drawable {
private Tile[][] map;
private int size;
private TiledMap tiledMap;
private MapLoader mapLoader;
private List<Tile> allTiles;
private List<Tile> tilesToDraw;
private List<Creature> creatures;
private List<Player> players;
private List<NonPlayer> NPCs;
private List<LightSource> lightSources;
private List<Item> items;
private List<Bullet> bullets;
private long timeOfLastPassTime;
public Area() {
size = 31;
map = new Tile[size][size];
allTiles = new LinkedList<Tile>();
tilesToDraw = new LinkedList<Tile>();
creatures = new LinkedList<Creature>();
players = new LinkedList<Player>();
NPCs = new LinkedList<NonPlayer>();
lightSources = new LinkedList<LightSource>();
items = new LinkedList<Item>();
bullets = new LinkedList<Bullet>();
mapLoader = new MapLoader();
try {
mapLoader.loadMap("PvP1", this);
} catch (FileNotFoundException ex) {
Logger.getLogger(Area.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Tile> getTiles() {
return allTiles;
}
public void addTile(Tile tile, int x, int y) {
tile.setArea(this);
tile.setPosition(x, y);
allTiles.add(tile);
map[x][y] = tile;
}
public int getSize() {
return size;
}
@Override
public void draw(Batch batch) {
drawTiles(batch);
drawBullets(batch);
drawCreatures(batch);
}
public void drawTiles(Batch batch) {
for (Iterator<Tile> it = tilesToDraw.iterator(); it.hasNext();) {
it.next().draw(batch);
it.remove();
}
}
public boolean hasLocation(float x, float y) {
return x >= 0 && x < size*Tile.size && y >= 0 && y < size*Tile.size;
}
public boolean hasLocation(int x, int y) {
return x >= 0 && x < size && y >= 0 && y < size;
}
public Tile getTileAt(float x, float y) {
int x0 = (int) ((x - (x % Tile.size)) / Tile.size);
int y0 = (int) ((y - (y % Tile.size)) / Tile.size);
return getTileAt(x0, y0);
}
public Tile getTileAt(int x, int y) {
return map[x][y];
}
public void addToDrawList(Tile tile) {
tilesToDraw.add(tile);
}
public void drawCreatures(Batch batch) {
batch.enableBlending();
for (Player player : players) {
for (Creature creature : NPCs) {
if (creature.canBeSeenBy(player)) {
creature.draw(batch);
}
}
player.draw(batch);
}
batch.disableBlending();
}
public void drawBullets(Batch batch) {
batch.enableBlending();
for (Player player : players) {
for (Bullet bullet : bullets) {
if (bullet.canBeSeenBy(player)) {
bullet.draw(batch);
}
}
}
batch.disableBlending();
}
public void calculateFOV() {
for (Player player : players) {
if (!player.canSeeEverything()) {
for (Tile tile : allTiles) {
if (tile.canBeSeenBy(player)) {
tile.requestDraw();
}
}
} else {
for (Tile tile : allTiles) {
tilesToDraw.add(tile);
}
}
}
}
public void calculateLighting() {
for (Player player : players) {
if (player.canSeeEverything()) {
Color color = new Color(1, 1, 1, 1);
for (Tile tile : allTiles) {
tile.setLighting(color);
}
} else {
float x = player.getX();
float y = player.getY();
int range = player.getSight();
for (Tile tile : allTiles) {
if (tile.canBeSeenBy(player)) {
Color color = new Color(1, 1, 1, 1);
float distance = tile.getDistanceTo(x, y) / Tile.size;
float multiplier = 1f - Math.max(distance-1, 0) * (1f/range);
color.mul(multiplier, multiplier, multiplier, 1f);
tile.setLighting(color);
}
}
}
}
}
public void addCreature(Creature guy) {
// Places creature to a random tile that has no object in it.
// If every tile has an object, this will loop infinitely.
Tile dest;
do {
dest = map[MathUtils.random(size-1)][MathUtils.random(size-1)];
} while (dest.hasObject());
addCreature(guy, dest.getX(), dest.getY());
}
public void addCreature(Creature guy, int x, int y) {
guy.setArea(this);
guy.setPosition(x*Tile.size+Tile.size/2, y*Tile.size+Tile.size/2);
guy.updateSpritePosition();
creatures.add(guy);
if (guy.getClass() == Player.class) {
players.add((Player) guy);
} else {
NPCs.add((NonPlayer) guy);
}
}
public void removeCreature(Creature creature) {
creatures.remove(creature);
if (!creature.isPlayer()) {
NPCs.remove((NonPlayer) creature);
} else {
players.remove((Player) creature);
}
}
public void addLightSource(LightSource light) {
light.setArea(this);
lightSources.add(light);
}
public void addItem(Item item, int x, int y) {
items.add(item);
map[x][y].setObject(item);
}
public void addItem(Item item) {
// Adds item to a random tile that has no object yet.
// If every tile has an object, this will loop infinitely.
Tile dest;
do {
dest = map[MathUtils.random(size-1)][MathUtils.random(size-1)];
} while (dest.hasObject());
addItem(item, dest.getX(), dest.getY());
}
public List<Creature> getCreatures() {
return creatures;
}
public List<Player> getPlayers() {
return players;
}
public List<NonPlayer> getNPCs() {
return NPCs;
}
public List<Bullet> getBullets() {
return bullets;
}
public void addBullet(Bullet bullet) {
bullet.setArea(this);
bullets.add(bullet);
}
public void removeBullet(Bullet bullet) {
bullets.remove(bullet);
}
public void passTime(float delta) {
long currentTime = TimeUtils.millis();
if (currentTime - timeOfLastPassTime > 100) {
for (Creature creature : creatures) {
Tile tileUnderCreature = getTileAt(creature.getX(), creature.getY());
if (tileUnderCreature.drainsHP()) {
creature.dealDamage((int) (tileUnderCreature.getHPDrainAmount()));
}
creature.regenerateHP(currentTime);
}
timeOfLastPassTime = currentTime;
}
}
public static int floatPosToTilePos(float pos) {
return (int) ((pos - (pos % Tile.size)) / Tile.size);
}
}
|
package aQute.libg.version;
import java.util.regex.*;
public class Version implements Comparable<Version> {
final int major;
final int minor;
final int micro;
final String qualifier;
public final static String VERSION_STRING = "(\\d+)(\\.(\\d+)(\\.(\\d+)(\\.([-_\\da-zA-Z]+))?)?)?";
public final static Pattern VERSION = Pattern
.compile(VERSION_STRING);
public final static Version LOWEST = new Version();
public final static Version HIGHEST = new Version(Integer.MAX_VALUE,
Integer.MAX_VALUE,
Integer.MAX_VALUE,
"\uFFFF");
public static final Version emptyVersion = LOWEST;
public Version() {
this(0);
}
public Version(int major, int minor, int micro, String qualifier) {
this.major = major;
this.minor = minor;
this.micro = micro;
this.qualifier = qualifier;
}
public Version(int major, int minor, int micro) {
this(major, minor, micro, null);
}
public Version(int major, int minor) {
this(major, minor, 0, null);
}
public Version(int major) {
this(major, 0, 0, null);
}
public Version(String version) {
Matcher m = VERSION.matcher(version);
if (!m.matches())
throw new IllegalArgumentException("Invalid syntax for version: "
+ version);
major = Integer.parseInt(m.group(1));
if (m.group(3) != null)
minor = Integer.parseInt(m.group(3));
else
minor = 0;
if (m.group(5) != null)
micro = Integer.parseInt(m.group(5));
else
micro = 0;
qualifier = m.group(7);
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getMicro() {
return micro;
}
public String getQualifier() {
return qualifier;
}
public int compareTo(Version other) {
if (other == this)
return 0;
if (!(other instanceof Version))
throw new IllegalArgumentException(
"Can only compare versions to versions");
Version o = (Version) other;
if (major != o.major)
return major - o.major;
if (minor != o.minor)
return minor - o.minor;
if (micro != o.micro)
return micro - o.micro;
int c = 0;
if (qualifier != null)
c = 1;
if (o.qualifier != null)
c += 2;
switch (c) {
case 0:
return 0;
case 1:
return 1;
case 2:
return -1;
}
return qualifier.compareTo(o.qualifier);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(major);
sb.append(".");
sb.append(minor);
sb.append(".");
sb.append(micro);
if (qualifier != null) {
sb.append(".");
sb.append(qualifier);
}
return sb.toString();
}
public boolean equals(Object ot) {
if ( ! (ot instanceof Version))
return false;
return compareTo((Version)ot) == 0;
}
public int hashCode() {
return major * 97 ^ minor * 13 ^ micro
+ (qualifier == null ? 97 : qualifier.hashCode());
}
public int get(int i) {
switch(i) {
case 0 : return major;
case 1 : return minor;
case 2 : return micro;
default:
throw new IllegalArgumentException("Version can only get 0 (major), 1 (minor), or 2 (micro)");
}
}
public static Version parseVersion(String version) {
if (version == null) {
return LOWEST;
}
version = version.trim();
if (version.length() == 0) {
return LOWEST;
}
return new Version(version);
}
}
|
import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.Command;
import com.github.sormuras.bach.Configuration;
import com.github.sormuras.bach.ExternalModuleLocators;
import com.github.sormuras.bach.ToolCall;
import com.github.sormuras.bach.ToolFinder;
import com.github.sormuras.bach.command.JarCommand;
import com.github.sormuras.bach.external.JUnit;
import java.lang.module.ModuleDescriptor.Version;
import java.lang.module.ModuleFinder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
class build {
public static void main(String... args) {
System.setProperty("java.util.logging.config.file", ".bach/logging.properties");
System.out.println("BEGIN");
try (var bach = new Bach(args)) {
var version = version(bach);
bach.logCaption("Grab required and missing external modules");
var grabber = bach.grabber(locators());
grabber.grabExternalModules(
"org.junit.jupiter", "org.junit.platform.console", "org.junit.platform.jfr");
grabber.grabMissingExternalModules();
bach.logCaption("Grab external tools");
bach.run("grab", grab -> grab.add(bach.path().root(".bach", "external.properties")));
bach.logCaption("Build main code space");
var mainModules = buildMainModules(bach, version);
bach.logCaption("Build test code space");
var testModules = buildTestModules(bach, version, mainModules);
executeTests(bach, "com.github.sormuras.bach", mainModules, testModules);
executeTests(bach, "test.base", mainModules, testModules);
executeTests(bach, "test.integration", mainModules, testModules);
executeTests(bach, "test.projects", mainModules, testModules);
bach.logCaption("Generate documentation");
generateApiDocumentation(bach, version);
}
System.out.println("END.");
}
static ExternalModuleLocators locators() {
return ExternalModuleLocators.of(build::locate, JUnit.version("5.8.1"));
}
static String locate(String module) {
return switch (module) {
case "org.apiguardian.api" -> "https://repo.maven.apache.org/maven2/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar#SIZE=6806";
case "org.junit.jupiter" -> "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter/5.8.1/junit-jupiter-5.8.1.jar#SIZE=6361";
case "org.junit.jupiter.api" -> "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-api/5.8.1/junit-jupiter-api-5.8.1.jar#SIZE=193501";
case "org.junit.jupiter.engine" -> "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.8.1/junit-jupiter-engine-5.8.1.jar#SIZE=229680";
case "org.junit.jupiter.params" -> "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-params/5.8.1/junit-jupiter-params-5.8.1.jar#SIZE=575854";
case "org.junit.platform.commons" -> "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-commons/1.8.1/junit-platform-commons-1.8.1.jar#SIZE=100451";
case "org.junit.platform.console" -> "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-console/1.8.1/junit-platform-console-1.8.1.jar#SIZE=488164";
case "org.junit.platform.engine" -> "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-engine/1.8.1/junit-platform-engine-1.8.1.jar#SIZE=185778";
case "org.junit.platform.launcher" -> "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-launcher/1.8.1/junit-platform-launcher-1.8.1.jar#SIZE=159560";
case "org.junit.platform.reporting" -> "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-reporting/1.8.1/junit-platform-reporting-1.8.1.jar#SIZE=26175";
case "org.opentest4j" -> "https://repo.maven.apache.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar#SIZE=7653";
default -> null;
};
}
static Version version(Bach bach) {
var version = bach.configuration().projectOptions().version();
if (version.isPresent()) return version.get();
var file = Path.of("VERSION");
try {
return Version.parse(Files.readString(file) + "-ea");
} catch (Exception exception) {
throw new RuntimeException("Reading VERSION file failed: " + file.toUri(), exception);
}
}
static Path buildMainModules(Bach bach, Version version) {
var classes = Path.of(".bach/workspace/classes");
bach.run(
Command.javac()
.release(17)
.modules("com.github.sormuras.bach")
.moduleSourcePathPatterns("./*/main/java")
.add("-g")
.add("-parameters")
.add("-Werror")
.add("-Xlint")
.add("-encoding", "UTF-8")
.outputDirectoryForClasses(classes));
var modules = Path.of(".bach/workspace/modules");
bach.run(ToolCall.of("directories", "create", modules));
var file = Configuration.computeJarFileName("com.github.sormuras.bach", version);
bach.run(
Command.jar()
.mode("--create")
.file(modules.resolve(file))
.verbose(true)
.add("--module-version", version)
.main("com.github.sormuras.bach.Main")
.filesAdd(classes.resolve("com.github.sormuras.bach"))
.filesAdd(Path.of("com.github.sormuras.bach").resolve("main/java")));
return modules;
}
static Path buildTestModules(Bach bach, Version version, Path mainModules) {
var names =
List.of("test.base", "test.integration", "test.projects", "com.github.sormuras.bach");
var mainClasses = Path.of(".bach/workspace/classes");
var testClasses = Path.of(".bach/workspace/test-classes");
bach.run(
Command.javac()
.modules(names)
.moduleSourcePathPatterns("./*/test/java", "./*/test/java-module")
.modulePaths(mainModules, bach.path().externalModules())
.add(
"--patch-module",
"com.github.sormuras.bach=" + mainClasses.resolve("com.github.sormuras.bach"))
.add("-g")
.add("-parameters")
.add("-Werror")
.add("-Xlint")
.add("-encoding", "UTF-8")
.outputDirectoryForClasses(testClasses));
var modules = Path.of(".bach/workspace/test-modules");
bach.run(ToolCall.of("directories", "create", modules));
var jars = new ArrayList<JarCommand>();
for (var name : names) {
var file = name + "@" + version + "+test.jar";
var jar =
Command.jar()
.mode("--create")
.file(modules.resolve(file))
.add("--module-version", version + "+test")
.filesAdd(testClasses.resolve(name));
if (name.equals("com.github.sormuras.bach")) {
jar = jar.filesAdd(mainClasses.resolve("com.github.sormuras.bach"));
}
var resources = Path.of(name, "test", "resources");
if (Files.isDirectory(resources)) {
jar = jar.filesAdd(resources);
}
jars.add(jar);
}
jars.parallelStream().forEach(bach::run);
return modules;
}
static void executeTests(Bach bach, String module, Path mainModules, Path testModules) {
bach.logCaption("Execute tests of module " + module);
var moduleFinder =
ModuleFinder.of(
testModules.resolve(module + "@" + version(bach) + "+test.jar"),
mainModules,
testModules,
bach.path().externalModules());
var toolFinder = ToolFinder.of(moduleFinder, true, module);
bach.run(
ToolCall.of(
toolFinder,
Command.of("junit")
.add("--select-module", module)
.add("--reports-dir", Path.of(".bach/workspace/test-reports/junit-" + module))));
}
static void generateApiDocumentation(Bach bach, Version version) {
var api = bach.path().workspace("documentation", "api");
bach.run(
Command.of("javadoc")
.add("--module", "com.github.sormuras.bach")
.add("--module-source-path", "./*/main/java")
.add("-encoding", "UTF-8")
.add("-windowtitle", " Bach " + version)
.add("-header", " Bach %s API documentation".formatted(version))
.add("-notimestamp")
.add("-use")
.add("-linksource")
.add("-Xdoclint:-missing")
.add("-Werror")
.add("-d", api));
bach.run(
Command.jar()
.mode("--create")
.file(api.getParent().resolve("api.zip"))
.add("--no-manifest")
.filesAdd(api));
}
}
|
package logic;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
import model.Cell;
import model.Grid;
import model.Position;
/**
* The Class Maze.
*/
public class Maze implements Serializable
{
private static final long serialVersionUID = 1L; // default
static final Path PATH = new Path();
static final Wall WALL = new Wall();
/** The Grid. */
private final Grid<InanimatedObject> _board;
private final Set<Unit> _livingObjects;
private final PriorityQueue<UnitEvent> _eventQueue;
/**
* Instantiates an empty maze.
*
* @param width the width of the maze.
* @param height the height of the maze.
*/
public Maze(int width, int height)
{
_board = new Grid<InanimatedObject>(width, height, PATH);
_livingObjects = new TreeSet<Unit>(new UnitComparator());
_eventQueue = new PriorityQueue<UnitEvent>();
}
public int GetWidth() { return _board.Width; }
public int GetHeight() { return _board.Height; }
public int GetNumberOfPathCells()
{
int res = 0;
for (int x = 0; x < _board.Width; x++)
for (int y = 0; y < _board.Height; y++)
if (_board.GetCellT(x, y).equals(PATH))
res++;
return res;
}
public int GetNumberOfWallCells()
{
return _board.Width * _board.Height - GetNumberOfPathCells();
}
public Grid<InanimatedObject> GetGrid() { return _board; }
public Set<Unit> GetLivingObjects() { return _livingObjects; }
@Override
public String toString()
{
char[] result = _board.toString().toCharArray();
for (Unit u : _livingObjects)
{
Position p = u.GetPosition();
result[p.Y * (GetWidth() * 2) + p.X * 2] = u.GetSymbol();
}
return String.copyValueOf(result);
}
public void SendEagleToSword()
{
Hero h = FindHero();
Sword s = FindSword();
Eagle e = FindEagle();
PushEvent(e, new SendEagleEvent(h, s));
}
public void PushEvent(Unit u, Event ev)
{
_eventQueue.add(new UnitEvent(u, ev));
}
public void MoveHero(Direction direction)
{
PushEvent(FindHero(), new RequestMovementEvent(direction));
}
public void Update()
{
for (Unit wo : _livingObjects)
wo.Update(this);
while (!_eventQueue.isEmpty())
_eventQueue.poll().HandleEvent(this);
for (Iterator<Unit> uit = _livingObjects.iterator(); uit.hasNext();)
if (!uit.next().IsAlive())
uit.remove();
}
public void AddWorldObject(WorldObject obj)
{
if (obj.IsInanimatedObject())
_board.SetCell(obj.GetPosition(), obj.ToInanimatedObject());
else if (obj.IsUnit())
_livingObjects.add(obj.ToUnit());
}
public boolean IsFinished()
{
Hero h = FindHero();
return h == null || h.GetPosition().equals(FindExitPortal().GetPosition());
}
public Hero FindHero()
{
for (Unit wo : _livingObjects)
if (wo.IsHero())
return wo.ToHero();
return null;
}
public Eagle FindEagle()
{
for (Unit wo : _livingObjects)
if (wo.IsEagle())
return wo.ToEagle();
return null;
}
public Sword FindSword()
{
for (Unit wo : _livingObjects)
if (wo.IsSword())
return wo.ToSword();
return null;
}
public ArrayList<Dragon> FindDragons()
{
ArrayList<Dragon> r = new ArrayList<Dragon>();
for (Unit wo : _livingObjects)
if (wo.IsDragon())
r.add(wo.ToDragon());
return r;
}
public ExitPortal FindExitPortal()
{
for (int x = 0; x < GetWidth(); ++x)
{
for (int y = 0; y < GetHeight(); ++y)
{
if (_board.GetCellT(x, y).IsExitPortal())
return _board.GetCellT(x, y).ToExitPortal();
}
}
return null;
}
public boolean IsEmptyPosition(Position p)
{
if (!IsPathPosition(p))
return false;
for (Unit u : _livingObjects)
if (u.GetPosition().equals(p))
return false;
return true;
}
public boolean IsPathPosition(Position p)
{
Cell<InanimatedObject> c = _board.GetCell(p);
return c != null ? c.GetValue().IsPath() : null;
}
public void ForwardEventToUnits(Event ev)
{
for (Unit u : _livingObjects)
PushEvent(u, ev);
}
public boolean IsExitPosition(Position newPos)
{
ExitPortal ex = FindExitPortal();
return ex != null && newPos != null && newPos.equals(ex.GetPosition());
}
}
|
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class GpioMMapTest {
private static final boolean READ_ONLY = true;
private static final int SIZE_OF_INT = 4;
static {
System.loadLibrary("gpiommaptest");
}
private static final int PI_MAX_GPIO = 53;
private static final int GPIO_LEN = 0xB4;
/*
0 GPFSEL0 GPIO Function Select 0
1 GPFSEL1 GPIO Function Select 1
2 GPFSEL2 GPIO Function Select 2
3 GPFSEL3 GPIO Function Select 3
4 GPFSEL4 GPIO Function Select 4
5 GPFSEL5 GPIO Function Select 5
6 - Reserved
7 GPSET0 GPIO Pin Output Set 0
8 GPSET1 GPIO Pin Output Set 1
9 - Reserved
10 GPCLR0 GPIO Pin Output Clear 0
11 GPCLR1 GPIO Pin Output Clear 1
12 - Reserved
13 GPLEV0 GPIO Pin Level 0
14 GPLEV1 GPIO Pin Level 1
15 - Reserved
16 GPEDS0 GPIO Pin Event Detect Status 0
17 GPEDS1 GPIO Pin Event Detect Status 1
18 - Reserved
19 GPREN0 GPIO Pin Rising Edge Detect Enable 0
20 GPREN1 GPIO Pin Rising Edge Detect Enable 1
21 - Reserved
22 GPFEN0 GPIO Pin Falling Edge Detect Enable 0
23 GPFEN1 GPIO Pin Falling Edge Detect Enable 1
24 - Reserved
25 GPHEN0 GPIO Pin High Detect Enable 0
26 GPHEN1 GPIO Pin High Detect Enable 1
27 - Reserved
28 GPLEN0 GPIO Pin Low Detect Enable 0
29 GPLEN1 GPIO Pin Low Detect Enable 1
30 - Reserved
31 GPAREN0 GPIO Pin Async. Rising Edge Detect 0
32 GPAREN1 GPIO Pin Async. Rising Edge Detect 1
33 - Reserved
34 GPAFEN0 GPIO Pin Async. Falling Edge Detect 0
35 GPAFEN1 GPIO Pin Async. Falling Edge Detect 1
36 - Reserved
37 GPPUD GPIO Pin Pull-up/down Enable
38 GPPUDCLK0 GPIO Pin Pull-up/down Enable Clock 0
39 GPPUDCLK1 GPIO Pin Pull-up/down Enable Clock 1
40 - Reserved
41 - Test
*/
private static final int GPSET0 = 7;
private static final int GPSET1 = 8;
private static final int GPCLR0 = 10;
private static final int GPCLR1 = 11;
private static final int GPLEV0 = 13;
private static final int GPLEV1 = 14;
private static final int PI_OFF = 0;
private static final int PI_ON = 1;
private static final int PI_CLEAR = 0;
private static final int PI_SET = 1;
private static final int PI_LOW = 0;
private static final int PI_HIGH = 1;
private static final int PI_INPUT = 0;
private static final int PI_OUTPUT = 1;
private static final int PI_ALT0 = 4;
private static final int PI_ALT1 = 5;
private static final int PI_ALT2 = 6;
private static final int PI_ALT3 = 7;
private static final int PI_ALT4 = 3;
private static final int PI_ALT5 = 2;
private static final int PI_PUD_OFF = 0;
private static final int PI_PUD_DOWN = 1;
private static final int PI_PUD_UP = 2;
public static native ByteBuffer initialise();
public static native void test();
public static native void terminate();
//static volatile uint32_t * gpioReg = MAP_FAILED;
private static ByteBuffer gpioReg = null;
public static void main(String[] args) {
int gpio = 12;
try {
gpioReg = initialise();
if (gpioReg == null) {
System.out.println("Error in initialise");
return;
}
System.out.println("capacity=" + gpioReg.capacity());
System.out.println("order=" + gpioReg.order());
gpioReg.order(ByteOrder.LITTLE_ENDIAN);
System.out.println("order=" + gpioReg.order());
for (int i=0; i<20; i++) {
System.out.format("gpioReg[%d]=0x%x%n", i, gpioReg.getInt(i*4));
}
for (int i=0; i<20; i++) {
System.out.format("gpioReg[%d]=0x", i);
for (int j=3; j>=0; j
System.out.format("%02x", gpioReg.get(i*4+j));
}
System.out.println();
}
test();
for (int i=0; i<gpioReg.capacity()/SIZE_OF_INT; i+=4) {
if ((i % 0x1000) == 0) {
System.out.format("gpioReg[%d]=0x%x%n", i, gpioReg.getInt(i));
}
if (gpioReg.getInt(i) == 0x24024) {
System.out.format("gpioReg[0x%x]=0x%x%n", i, gpioReg.getInt(i));
System.out.println("Found it...");
break;
}
}
int rc = gpioSetMode(gpio, PI_OUTPUT);
if (rc < 0) {
System.out.println("Error in gpioSetMode()");
return;
}
delay(1000);
System.out.println("Turning GPIO " + gpio + " on");
rc = gpioWrite(gpio, PI_ON);
if (rc < 0) {
System.out.println("Error in gpioWrite()");
return;
}
delay(1000);
System.out.println("Turning GPIO " + gpio + " off");
rc = gpioWrite(gpio, PI_OFF);
if (rc < 0) {
System.out.println("Error in gpioWrite()");
return;
}
delay(1000);
} finally {
gpioReg = null;
terminate();
}
}
public static int gpioSetMode(int gpio, int mode) {
System.out.println("gpioSetMode(" + gpio + ", " + mode + ")");
if (gpio > PI_MAX_GPIO || gpio < 0) {
return -1;
}
if (mode > PI_ALT3 || mode < 0) {
return -2;
}
int reg = gpio / 10;
int shift = (gpio%10) * 3;
int old_reg_val = gpioReg.getInt(reg*4);
int old_mode = (old_reg_val >> shift) & 7;
System.out.println("reg=" + reg + ", shift=" + shift + ", old_reg_val=" + old_reg_val + ", old_mode=" + old_mode);
if (mode != old_mode) {
//switchFunctionOff(gpio);
int new_mode = (old_reg_val & ~(7<<shift)) | (mode<<shift);
System.out.println("new_mode=" + new_mode);
if (READ_ONLY) {
System.out.println("READ_ONLY flag is true, not writing anything");
return -1;
}
gpioReg.putInt(reg, new_mode);
}
return 0;
}
public static int gpioWrite(int gpio, int level) {
if (gpio > PI_MAX_GPIO || gpio < 0) {
return -1;
}
if (level > PI_ON || level < 0) {
return -2;
}
int BIT = 1 << (gpio & 0x1F);
int BANK = gpio >> 5;
if (READ_ONLY) {
System.out.println("READ_ONLY flag is true, not writing anything");
return -3;
}
if (level == PI_OFF) {
gpioReg.putInt(GPCLR0 + BANK, BIT);
} else {
gpioReg.putInt(GPSET0 + BANK, BIT);
}
return 0;
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
}
}
|
package dk.statsbiblioteket.doms.updatetracker.webservice;
import dk.statsbiblioteket.doms.webservices.Credentials;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.WebServiceContext;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.net.MalformedURLException;
/**
* Update tracker webservice. Provides upper layers of DOMS with info on changes
* to objects in Fedora. Used by DOMS Server aka. Central to provide Summa with
* said info.
*/
@WebService(endpointInterface
= "dk.statsbiblioteket.doms.updatetracker.webservice"
+ ".UpdateTrackerWebservice")
public class UpdateTrackerWebserviceImpl implements UpdateTrackerWebservice{
@Resource
WebServiceContext context;
private XMLGregorianCalendar lastChangedTime;
public UpdateTrackerWebserviceImpl() throws MethodFailedException {
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone(
"Europe/Copenhagen"));
calendar.set(GregorianCalendar.YEAR, 1999);
calendar.set(GregorianCalendar.MONTH, 12);
calendar.set(GregorianCalendar.DAY_OF_MONTH, 31);
calendar.set(GregorianCalendar.HOUR_OF_DAY, 23);
calendar.set(GregorianCalendar.MINUTE, 59);
calendar.set(GregorianCalendar.SECOND, 59);
calendar.set(GregorianCalendar.MILLISECOND, 999);
try {
lastChangedTime
= DatatypeFactory.newInstance().newXMLGregorianCalendar(
calendar);
} catch (DatatypeConfigurationException e) {
throw new MethodFailedException(
"Could not make new XMLGregorianCalendar", "");
}
}
/**
* Lists the entry objects of views (records) in Fedora, in the given
* collection, that have changed since the given time.
*
* @param collectionPid The PID of the collection in which we are looking
* for changes.
* @param entryCMPid The PID of the content model which all listed records
* should adhere to.
* @param viewAngle ...TODO doc
* @param beginTime The time since which we are looking for changes.
* @return returns java.util.List<dk.statsbiblioteket.doms.updatetracker
* .webservice.PidDatePidPid>
*
* @throws MethodFailedException
* @throws InvalidCredentialsException
*
*/
public List<PidDatePidPid> listObjectsChangedSince(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle,
@WebParam(name = "beginTime", targetNamespace = "")
XMLGregorianCalendar beginTime)
throws InvalidCredentialsException, MethodFailedException {
// TODO Un-mockup this class please :-)
List<PidDatePidPid> result = new ArrayList<PidDatePidPid>();
// Mockup: If wanted beginTime is AFTER our hardcoded lastChangedTime,
// we just return no objects/views/records at all.
if (beginTime.toGregorianCalendar().after(
lastChangedTime.toGregorianCalendar())) {
return result;
}
// Mockup: If wanted beginTime is BEFORE (or =) our hardcoded
// lastChangedTime, connect to ECM and get a list of all entry objects
// in (hardcoded:) our RadioTVCollection. Return all these.
String pidOfCollection = "doms:RadioTV_Collection";
List<String> allEntryObjectsInRadioTVCollection;
ECM ecmConnector;
try {
ecmConnector = new ECM(getCredentials(), "http://alhena:7980/ecm");
} catch (MalformedURLException e) {
throw new MethodFailedException("Malformed URL", "", e);
}
// TODO Mockup by calling the getAllEntryObjectsInCollection method in
// ECM with collectionPID to get <PID, collectionPID, entryPID>.
try {
allEntryObjectsInRadioTVCollection
= ecmConnector.getAllEntryObjectsInCollection(
pidOfCollection, viewAngle, entryCMPid);
} catch (BackendInvalidCredsException e) {
throw new InvalidCredentialsException("Invalid credentials", "", e);
} catch (BackendMethodFailedException e) {
throw new MethodFailedException("Method failed", "", e);
}
for (String pid : allEntryObjectsInRadioTVCollection) {
PidDatePidPid objectThatChanged = new PidDatePidPid();
objectThatChanged.setPid(pid);
objectThatChanged.setLastChangedTime(lastChangedTime);
objectThatChanged.setCollectionPid(collectionPid);
objectThatChanged.setEntryCMPid(entryCMPid);
result.add(objectThatChanged);
}
return result;
}
/**
* Return the last time a view/record conforming to the content model of the
* given content model entry, and in the given collection, has been changed.
*
* @param collectionPid The PID of the collection in which we are looking
* for the last change.
* @param entryCMPid The PID of the entry object of the content model which
* our changed record should adhere to.
* @param viewAngle ...TODO doc
* @return The date/time of the last change.
* @throws InvalidCredentialsException
* @throws MethodFailedException
*/
public XMLGregorianCalendar getLatestModificationTime(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle)
throws InvalidCredentialsException, MethodFailedException {
return lastChangedTime;
}
/**
* TODO doc
*
* @return TODO doc
*/
private Credentials getCredentials() {
HttpServletRequest request = (HttpServletRequest) context
.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
Credentials creds = (Credentials) request.getAttribute("Credentials");
if (creds == null) {
// log.warn("Attempted call at Central without credentials");
creds = new Credentials("", "");
}
return creds;
}
}
|
package graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import main.util.Utility;
import main.util.dataparser.DTSDParser;
import main.util.dataparser.DataParser;
import main.util.dataparser.TSDParser;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import analysis.AnalysisView;
import biomodel.parser.BioModel;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private AnalysisView reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock, lock2;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim,
String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
lock2 = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false);
applyChartTheme(chart);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
setChange(false);
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
Dimension dim = new Dimension(1,1);
XVariable.setPreferredSize(dim);
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (file.contains(".dtsd"))
graphSpecies = (new DTSDParser(file)).getSpecies();
else
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
ArrayList<String> runs = new ArrayList<String>();
if (directory == null) {
String[] files = new File(outDir).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
else {
String[] files = new File(outDir + separator + directory).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
boolean outputFile;
if (directory == null) {
outputFile = !(new File(outDir + separator + "running").exists());
}
else {
outputFile = !(new File(outDir + separator + directory + separator + "running").exists());
}
if (label.contains("average")) {
if (directory == null) {
outputFile = outputFile && !(new File(outDir + separator + "mean.tsd").exists());
}
else {
outputFile = outputFile
&& !(new File(outDir + separator + directory + separator + "mean.tsd").exists());
}
return calculateAverageVarianceDeviation(runs, 0, directory, warn, outputFile);
}
else if (label.contains("variance")) {
if (directory == null) {
outputFile = outputFile && !(new File(outDir + separator + "variance.tsd").exists());
}
else {
outputFile = outputFile
&& !(new File(outDir + separator + directory + separator + "variance.tsd").exists());
}
return calculateAverageVarianceDeviation(runs, 1, directory, warn, outputFile);
}
else {
if (directory == null) {
outputFile = outputFile && !(new File(outDir + separator + "standard_deviation.tsd").exists());
}
else {
outputFile = outputFile
&& !(new File(outDir + separator + directory + separator + "standard_deviation.tsd")
.exists());
}
return calculateAverageVarianceDeviation(runs, 2, directory, warn, outputFile);
}
}
//if it's not a stats file
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
DTSDParser dtsdParser;
TSDParser p;
ArrayList<ArrayList<Double>> data;
if (file.contains(".dtsd")) {
dtsdParser = new DTSDParser(file);
Gui.frame.setCursor(null);
warn = false;
graphSpecies = dtsdParser.getSpecies();
data = dtsdParser.getData();
}
else {
p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
data = p.getData();
}
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("recalculate")) {
TreePath select = tree.getSelectionPath();
String[] files;
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list();
}
else {
files = new File(outDir).list();
}
ArrayList<String> runs = new ArrayList<String>();
for (String file : files) {
if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(file);
}
}
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true);
}
else {
calculateAverageVarianceDeviation(runs, 0, null, warn, true);
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent()).getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j
}
}
}
else {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
simDir.remove(i);
}
else if (name.equals("Termination Time")) {
name = "term-time";
simDir.remove(i);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
simDir.remove(i);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
simDir.remove(i);
}
else {
simDir.remove(i);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
d = true;
}
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) {
simDir.remove(j);
j
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) {
simDir.remove(j);
j
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) {
simDir.remove(j);
j
}
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Termination Time")) {
name = "term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else {
((IconNode) simDir.getChildAt(i)).remove(j);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation"
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
d = true;
}
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
}
}
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
} else {
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setDomainAxis(domainAxis);
LogX.setSelected(false);
}
} else {
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setDomainAxis(domainAxis);
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
XYPlot plot = (XYPlot) chart.getXYPlot();
if (((JCheckBox) e.getSource()).isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setDomainAxis(domainAxis);
LogX.setSelected(false);
}
} else {
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setDomainAxis(domainAxis);
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
XYPlot plot = (XYPlot) chart.getXYPlot();
if (((JCheckBox) e.getSource()).isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
} else {
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean addMean = false;
boolean addVar = false;
boolean addDev = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
boolean addBif = false;
directories = new ArrayList<String>();
for (String file : files) {
if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) {
if (file.contains("run-") || file.contains("mean")) {
addMean = true;
}
else if (file.contains("run-") || file.contains("variance")) {
addVar = true;
}
else if (file.contains("run-") || file.contains("standard_deviation")) {
addDev = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else if (file.contains("bifurcation")) {
addBif = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// files3[j] = files3[j - 1];
// j = j - 1;
// files3[j] = index;
for (String getFile : files3) {
if ((getFile.length() > 3
&& (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if ((getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean addMean2 = false;
boolean addVar2 = false;
boolean addDev2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
boolean addBif2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8)) ||
f.contains(".dtsd")) {
if (f.contains("run-") || f.contains("mean")) {
addMean2 = true;
}
else if (f.contains("run-") || f.contains("variance")) {
addVar2 = true;
}
else if (f.contains("run-") || f.contains("standard_deviation")) {
addDev2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else if (f.contains("bifurcation")) {
addBif2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))
|| getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean addMean3 = false;
boolean addVar3 = false;
boolean addDev3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
boolean addBif3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))
|| f2.contains(".dtsd")) {
if (f2.contains("run-") || f2.contains("mean")) {
addMean3 = true;
}
else if (f2.contains("run-") || f2.contains("variance")) {
addVar3 = true;
}
else if (f2.contains("run-") || f2.contains("standard_deviation")) {
addDev3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else if (f2.contains("bifurcation")) {
addBif3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (addMean3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev3) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar3) {
IconNode n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif3) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator
+ (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (addMean2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev2) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar2) {
IconNode n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif2) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (addMean) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar) {
IconNode n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
scroll.getVerticalScrollBar().setUnitIncrement(10);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
setChange(true);
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) &&
(graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(outDir + separator + g.getRunNumber() + "." + extension,
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
//if the data has already been put into the data structure
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ extension, g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
//if it's one of the stats/termination files
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end average
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end variance
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end standard deviation
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end termination time
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end percent termination
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end constraint termination
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
} //end of "Ok" option being true
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName()) && node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else if (selected.equals("Bifurcation Statistics")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
//tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
//tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")
|| selected.equals("Bifurcation Statistics")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + selected + "." + extension).exists() == false)
extension = "dtsd";
readGraphSpecies(outDir + separator + selected + "." + extension);
}
}
else {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")
|| selected.equals("Bifurcation Statistics")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
specs = new JLabel("Variables");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(),
series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning,
boolean output) {
if (files.size() > 0) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data;
if (directory == null) {
data = readData(outDir + separator + files.get(0), "", directory, warn);
}
else {
data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn);
}
averageOrder = graphSpecies;
boolean first = true;
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
for (String run : files) {
if (directory == null) {
if (new File(outDir + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
else {
if (new File(outDir + separator + directory + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (output) {
DataParser m = new DataParser(graphSpecies, average);
DataParser d = new DataParser(graphSpecies, deviation);
DataParser v = new DataParser(graphSpecies, variance);
if (directory == null) {
m.outputTSD(outDir + separator + "mean.tsd");
v.outputTSD(outDir + separator + "variance.tsd");
d.outputTSD(outDir + separator + "standard_deviation.tsd");
}
else {
m.outputTSD(outDir + separator + directory + separator + "mean.tsd");
v.outputTSD(outDir + separator + directory + separator + "variance.tsd");
d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd");
}
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
return null;
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
setChange(false);
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
setChange(false);
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
setChange(false);
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", ""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
setChange(false);
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next)
.trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), xnumber,
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next),
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
lock2.lock();
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
data = readData(
outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
lock2.unlock();
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species,
int xnumber, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public void setChange(boolean change) {
this.change = change;
biomodelsim.markTabDirty(change);
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false);
applyChartTheme(chart);
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
setChange(false);
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator + f).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f).list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory()
.equals(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
setChange(true);
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText()
.trim(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);
applyChartTheme(chart);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
BioModel gcm = new BioModel(biomodelsim.getRoot());
gcm.load(background);
learnSpecs = gcm.getSpecies();
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
/*
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
public static void applyChartTheme(JFreeChart chart) {
final StandardChartTheme chartTheme = (StandardChartTheme) org.jfree.chart.StandardChartTheme
.createJFreeTheme();
final Font oldExtraLargeFont = chartTheme.getExtraLargeFont();
final Font oldLargeFont = chartTheme.getLargeFont();
final Font oldRegularFont = chartTheme.getRegularFont();
final Font oldSmallFont = chartTheme.getSmallFont();
final Font extraLargeFont = new Font("Sans-serif", oldExtraLargeFont.getStyle(), oldExtraLargeFont.getSize());
final Font largeFont = new Font("Sans-serif", oldLargeFont.getStyle(), oldLargeFont.getSize());
final Font regularFont = new Font("Sans-serif", oldRegularFont.getStyle(), oldRegularFont.getSize());
final Font smallFont = new Font("Sans-serif", oldSmallFont.getStyle(), oldSmallFont.getSize());
chartTheme.setExtraLargeFont(extraLargeFont);
chartTheme.setLargeFont(largeFont);
chartTheme.setRegularFont(regularFont);
chartTheme.setSmallFont(smallFont);
chartTheme.apply(chart);
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
package org.intermine.web;
import org.intermine.metadata.Model;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.util.TypeUtil;
/**
* Superclass of left and right nodes
* @author Mark Woodbridge
*/
public class Node
{
String fieldName, path, prefix, type, parentType;
boolean attribute = false, reference = false, collection = false;
int indentation;
/**
* Constructor for a root node
* @param type the root type of this tree
*/
public Node(String type) {
this.type = type;
path = type;
prefix = "";
indentation = 0;
}
/**
* Constructor for a non-root node
* @param parent the parent node of this node
* @param fieldName the name of the field that this node represents
* @param model the model used to resolve paths
*/
public Node(Node parent, String fieldName, Model model) {
this.fieldName = fieldName;
prefix = parent.getPath();
path = prefix + "." + fieldName;
parentType = parent.getType();
ClassDescriptor cld = MainHelper.getClassDescriptor(parent.getType(), model);
if (cld == null) {
throw new RuntimeException("No class '" + parent.getType() + "' found in model"
+ " '" + model.getName() + "'");
}
FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName);
if (fd == null) {
throw new RuntimeException("Class '" + cld.getName() + "' does not have field"
+ " '" + fieldName + "'.");
}
type = TypeUtil.unqualifiedName(fd.isAttribute()
? ((AttributeDescriptor) fd).getType()
: ((ReferenceDescriptor) fd)
.getReferencedClassDescriptor().getType().getName());
attribute = fd.isAttribute();
reference = fd.isReference();
collection = fd.isCollection();
indentation = path.split("[.]").length - 1;
}
/**
* Type of parent node. Required for MainController to find field value
* enumerations with fieldName and parentType.
*
* @return type of parent node
*/
public String getParentType() {
return parentType;
}
/**
* Gets the value of path
*
* @return the value of path
*/
public String getPath() {
return path;
}
/**
* Gets the value of type
*
* @return the value of type
*/
public String getType() {
return type;
}
/**
* Set the value of type
*
* @param type the value of type
*/
public void setType(String type) {
this.type = type;
}
/**
* Gets the value of prefix
*
* @return the value of prefix
*/
public String getPrefix() {
return prefix;
}
/**
* Gets the value of fieldName
*
* @return the value of fieldName
*/
public String getFieldName() {
return fieldName;
}
/**
* Gets the value of attribute
*
* @return the value of attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
* Gets the value of reference
*
* @return the value of reference
*/
public boolean isReference() {
return reference;
}
/**
* Gets the value of collection
*
* @return the value of collection
*/
public boolean isCollection() {
return collection;
}
/**
* Gets the value of indentation
*
* @return the value of indentation
*/
public int getIndentation() {
return indentation;
}
/**
* @see Object#toString
*/
public String toString() {
return path + ":" + type;
}
/**
* @see Object#equals
*/
public boolean equals(Object o) {
return (o instanceof Node)
&& path.equals(((Node) o).path)
&& type.equals(((Node) o).type);
}
/**
* @see Object#hashCode
*/
public int hashCode() {
return 2 * path.hashCode()
+ 3 * type.hashCode();
}
}
|
package graph;
import gcm.parser.GCMFile;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import parser.TSDParser;
import reb2sac.Reb2Sac;
import util.Utility;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private Reb2Sac reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id,
String outDir, String time, Gui biomodelsim, String open, Log log, String graphName,
boolean timeSeries, boolean learnGraph) {
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1]
+ ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1]
+ ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset,
String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory,
boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean"))
|| (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
int counter = 1;
while (!(new File(file).exists())) {
file = file.substring(0, file.length() - getLast.length());
file += stem;
file += counter + "";
file += "." + printer_id.substring(0, printer_id.length() - 8);
counter++;
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(file, stem, 0, directory, warn);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(file, stem, 1, directory, warn);
}
else if (label.contains("deviation")) {
return calculateAverageVarianceDeviation(file, stem, 2, directory, warn);
}
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:",
"Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0
&& ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals(
"" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(
rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (!((IconNode) select.getLastPathComponent()).getName().equals("Average")
&& !((IconNode) select.getLastPathComponent()).getName().equals("Variance")
&& !((IconNode) select.getLastPathComponent()).getName().equals(
"Standard Deviation")
&& ((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select
.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator
+ ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent())
.getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(
((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j
}
}
}
else {
simDir.remove(i);
File dir = new File(outDir + separator
+ ((IconNode) select.getLastPathComponent()).getName()
+ "." + printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
count++;
}
}
if (count == 3) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
simDir.remove(j);
j
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select
.getLastPathComponent())) {
((IconNode) simDir.getChildAt(i)).remove(j);
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName()
+ separator
+ ((IconNode) select.getLastPathComponent()).getName()
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k))
.getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory
.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k))
.getChildCount() == 0) {
count++;
}
}
if (count == 3) {
File dir2 = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName());
if (dir2.isDirectory()) {
biomodelsim.deleteDir(dir2);
}
else {
dir2.delete();
}
directories.remove(((IconNode) simDir.getChildAt(i))
.getName());
for (int k = 0; k < graphed.size(); k++) {
if (graphed.get(k).getDirectory().equals(
((IconNode) simDir.getChildAt(i)).getName())) {
graphed.remove(k);
k
}
}
simDir.remove(i);
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average")
&& !((IconNode) simDir.getChildAt(i)).getName().equals("Variance")
&& !((IconNode) simDir.getChildAt(i)).getName().equals(
"Standard Deviation")) {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName() + "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average")
&& !((IconNode) simDir.getChildAt(i)).getName().equals("Variance")
&& !((IconNode) simDir.getChildAt(i)).getName().equals(
"Standard Deviation")) {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName() + "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis()
.getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis()
.getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot()
.getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(
Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis()
.getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot()
.getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(
Gui.frame,
"Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis()
.getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator
+ split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3
&& file.substring(file.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-") || file.contains("mean") || file.contains("variance")
|| file.contains("standard_deviation")) {
add = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(
0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4))
&& g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// files3[j] = files3[j - 1];
// j = j - 1;
// files3[j] = index;
for (String getFile : files3) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile)
.isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator
+ getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean add2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-") || f.contains("mean") || f.contains("variance")
|| f.contains("standard_deviation")) {
add2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f
.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString()
.compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4))
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f)
.list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"."
+ printer_id.substring(0, printer_id
.length() - 8))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean add3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id
.substring(0, printer_id.length() - 8))) {
if (f2.contains("run-") || f2.contains("mean")
|| f2.contains("variance")
|| f2.contains("standard_deviation")) {
add3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0,
f2.length() - 4), f2.substring(0,
f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString()
.compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(
f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(
d.getName() + separator
+ d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (add3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat")
|| end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer
.parseInt(s.substring(4, s.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8)), "run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p
.get("run-"
+ (i + 1)
+ "."
+ printer_id
.substring(
0,
printer_id
.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(
d.getName() + separator
+ d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(
d2.toString()) > 0)
|| new File(
outDir
+ separator
+ d.toString()
+ separator
+ (d.getChildAt(j).toString() + "." + printer_id
.substring(0, printer_id
.length() - 8)))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s
.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1)
+ "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(
(String) p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir
+ separator
+ (simDir.getChildAt(j).toString() + "." + printer_id
.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString()
.compareToIgnoreCase(
(String) p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph."
+ "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n
.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(new JPanel());
titlePanel2.add(LogY);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane
.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs "
+ "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot()
.getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average")
&& !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " "
+ g.getDirectory())) {
data = allData.get(g.getRunNumber() + " "
+ g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData
.put(g.getRunNumber() + " " + g.getDirectory(),
data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average")
&& !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator
+ "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator
+ "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator
+ "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory())
.list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " "
+ g.getDirectory())) {
data = allData.get(g.getRunNumber() + " "
+ g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber().toLowerCase(), g.getDirectory(),
false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData
.put(g.getRunNumber() + " " + g.getDirectory(),
data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())
&& node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName()
+ separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation") || selected.equals("Termination Time")
|| selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation") || selected.equals("Termination Time")
|| selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
if (biomodelsim.lema || biomodelsim.atacs) {
specs = new JLabel("Variables");
}
else {
specs = new JLabel("Species");
}
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k)
.setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k)
.setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName()
.equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName()
.equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName()
.equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i)
.getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected,
boxes.get(i).getName(), series.get(i).getText().trim(), XVariable
.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals(
"" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i)
.setBackground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
colorsButtons.get(i)
.setForeground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint("Custom_"
+ colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color",
((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY,
export, output);
if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!",
"Error", JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2,
options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY,
export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!",
"Error", JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2,
options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame,
"Data series do not have the same number of points!",
"Unable to Export Data File", JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame,
"Data series time points are not the same!",
"Unable to Export Data File", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile,
String fileStem, int choice, String directory, boolean warning) {
warn = warning;
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data = readData(startFile, "", directory, warn);
averageOrder = graphSpecies;
boolean first = true;
int runsToMake = 1;
String[] findNum = startFile.split(separator);
String search = findNum[findNum.length - 1];
int firstOne = Integer.parseInt(search.substring(4, search.length() - 4));
if (directory == null) {
for (String f : new File(outDir).list()) {
if (f.contains(fileStem)) {
try {
int tempNum = Integer.parseInt(f.substring(fileStem.length(),
f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
catch (Exception e) {
}
}
}
}
else {
for (String f : new File(outDir + separator + directory).list()) {
if (f.contains(fileStem)) {
try {
int tempNum = Integer.parseInt(f.substring(fileStem.length(),
f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
catch (Exception e) {
}
}
}
}
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
int skip = firstOne;
for (int j = 0; j < runsToMake; j++) {
if (!first) {
if (firstOne != 1) {
j
firstOne = 1;
}
boolean loop = true;
while (loop && j < runsToMake && (j + 1) != skip) {
if (directory == null) {
if (new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator
+ fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8), "",
directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
loop = false;
// count++;
}
else {
j++;
}
}
else {
if (new File(outDir + separator + directory + separator + fileStem
+ (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator
+ directory + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8), "",
directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
loop = false;
// count++;
}
else {
j++;
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1)
- data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1)
+ (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1)
- data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1)
+ (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old
+ (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data
.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", ""
+ ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", ""
+ ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", ""
+ ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", ""
+ ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint()
.getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint()
.getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator
+ graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", ""
+ ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", ""
+ ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", ""
+ ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient",
""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", ""
+ ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator
+ graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:",
"Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1]
.length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint()
.getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint()
.getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]
+ "/" + graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame,
"Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1]
.length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient",
""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof GradientBarPainter));
graph
.setProperty("shadow", ""
+ ((BarRenderer) chart.getCategoryPlot().getRenderer())
.getShadowsVisible());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i)
.getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]
+ "/" + probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph
.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot()
.setBackgroundPaint(
new Color(Integer.parseInt(graph
.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape."
+ next)), graph.getProperty("species.paint." + next).trim(), filled,
visible, connected, graph.getProperty("species.run.number." + next),
graph.getProperty("species.id." + next), graph
.getProperty("species.name." + next), xnumber, Integer
.parseInt(graph.getProperty("species.number." + next)), graph
.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph
.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot()
.setBackgroundPaint(
new Color(Integer.parseInt(graph
.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), Integer
.parseInt(graph.getProperty("species.number." + next)), graph
.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "standard_deviation"
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time"
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time"
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "sim-rep"
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator
+ "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator
+ "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator
+ "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(),
chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis()
.getLabel(), chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset,
rend);
}
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected,
String runNumber, String id, String species, int xnumber, int number,
String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(),
PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer())
.getShadowsVisible());
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile)
.isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator
+ getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(".txt")
&& getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator
+ f).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f)
.list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4),
f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(
d2.toString()) > 0)
|| new File(outDir + separator + d.toString()
+ separator
+ (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph."
+ "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent())
.getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n
.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel2.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane
.showOptionDialog(Gui.frame, all, "Edit Probability Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0)
&& graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory()
+ separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0)
&& graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(),
histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k)
.setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k)
.setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color,
boxes.get(i).getName(), series.get(i).getText().trim(), i,
directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals(
"" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i)
.setBackground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
colorsButtons.get(i)
.setForeground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource())
.getSelectedItem());
g.setPaint(colory
.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_"
+ colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color",
((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel,
DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(),
chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot()
.getRangeAxis().getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator
+ split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir
.substring(0, outDir.length() - split[split.length - 1].length())
+ separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir
.substring(0, outDir.length() - split[split.length - 1].length())
+ separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
GCMFile gcm = new GCMFile(biomodelsim.getRoot());
gcm.load(background);
HashMap<String, Properties> speciesMap = gcm.getSpecies();
for (String s : speciesMap.keySet()) {
learnSpecs.add(s);
}
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
/*
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number,
String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
package org.opennms.features.topology.app.internal;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.opennms.features.topology.api.DisplayState;
import org.opennms.features.topology.api.TopologyProvider;
import org.opennms.features.topology.app.internal.TopoContextMenu.TopoContextMenuItem;
import org.opennms.features.topology.app.internal.jung.KKLayoutAlgorithm;
import org.opennms.features.topology.app.internal.support.FilterableHierarchicalContainer;
import org.opennms.features.topology.app.internal.support.IconRepositoryManager;
import com.github.wolfie.refresher.Refresher;
import com.vaadin.Application;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Slider;
import com.vaadin.ui.Slider.ValueOutOfBoundsException;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.Reindeer;
public class TopologyWidgetTestApplication extends Application implements CommandUpdateListener, MenuItemUpdateListener, ContextMenuHandler{
private Window m_window;
private TopologyComponent m_topologyComponent;
private Tree m_tree;
private SimpleGraphContainer m_graphContainer;
private CommandManager m_commandManager;
private MenuBar m_menuBar;
private TopoContextMenu m_contextMenu;
private AbsoluteLayout m_layout;
private IconRepositoryManager m_iconRepositoryManager;
public TopologyWidgetTestApplication(CommandManager commandManager, TopologyProvider topologyProvider, IconRepositoryManager iconRepoManager) {
m_commandManager = commandManager;
m_commandManager.addMenuItemUpdateListener(this);
m_graphContainer = new SimpleGraphContainer();
m_graphContainer.setDataSource(topologyProvider);
m_iconRepositoryManager = iconRepoManager;
}
@Override
public void init() {
setTheme("topo_default");
m_layout = new AbsoluteLayout();
m_layout.setSizeFull();
m_window = new Window("Topology Widget Test");
m_window.setContent(m_layout);
setMainWindow(m_window);
Refresher refresher = new Refresher();
refresher.setRefreshInterval(5000);
getMainWindow().addComponent(refresher);
m_graphContainer.setLayoutAlgorithm(new KKLayoutAlgorithm());
m_topologyComponent = new TopologyComponent(m_graphContainer);
m_topologyComponent.setIconRepoManager(m_iconRepositoryManager);
m_topologyComponent.setSizeFull();
m_topologyComponent.addMenuItemStateListener(this);
m_topologyComponent.setContextMenuHandler(this);
final Property scale = m_graphContainer.getProperty(DisplayState.SCALE);
final Slider slider = new Slider(0, 4);
slider.setResolution(2);
slider.setHeight("300px");
slider.setOrientation(Slider.ORIENTATION_VERTICAL);
try {
slider.setValue(1.0);
} catch (ValueOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scale.setValue(1.0);
slider.addListener(new ValueChangeListener(){
public void valueChange(ValueChangeEvent event) {
scale.setValue((Double) slider.getValue());
}
});
slider.setImmediate(true);
Label semanticZoomLabel = new Label();
final Property zoomLevel = m_graphContainer.getProperty(DisplayState.SEMANTIC_ZOOM_LEVEL);
semanticZoomLabel.setPropertyDataSource(zoomLevel);
NativeButton zoomInBtn = new NativeButton("+");
zoomInBtn.addListener(new ClickListener() {
public void buttonClick(ClickEvent event) {
int szl = (Integer) zoomLevel.getValue();
szl++;
zoomLevel.setValue(szl);
m_graphContainer.redoLayout();
}
});
NativeButton zoomOutBtn = new NativeButton("-");
zoomOutBtn.addListener(new ClickListener() {
public void buttonClick(ClickEvent event) {
int szl = (Integer) zoomLevel.getValue();
szl
zoomLevel.setValue(szl);
m_graphContainer.redoLayout();
}
});
AbsoluteLayout mapLayout = new AbsoluteLayout();
mapLayout.addComponent(m_topologyComponent, "top:0px; left: 0px; right: 0px; bottom: 0px;");
mapLayout.addComponent(slider, "top: 20px; left: 20px; z-index:1000;");
mapLayout.addComponent(semanticZoomLabel, "bottom: 10px; right: 10px; z-index: 2000;");
mapLayout.addComponent(zoomInBtn, "top: 0px; left: 0px;");
mapLayout.addComponent(zoomOutBtn, "top: 0px; left: 25px");
mapLayout.setSizeFull();
HorizontalSplitPanel treeMapSplitPanel = new HorizontalSplitPanel();
treeMapSplitPanel.setFirstComponent(createWestLayout());
treeMapSplitPanel.setSecondComponent(mapLayout);
treeMapSplitPanel.setSplitPosition(200, Sizeable.UNITS_PIXELS);
treeMapSplitPanel.setSizeFull();
VerticalSplitPanel bottomLayoutBar = new VerticalSplitPanel();
bottomLayoutBar.setFirstComponent(treeMapSplitPanel);
VerticalLayout zoomLayout = new VerticalLayout();
// zoomLayout.addComponent(zoomInBtn);
// zoomLayout.addComponent(zoomOutBtn);
bottomLayoutBar.setSecondComponent(zoomLayout);
bottomLayoutBar.setSplitPosition(99, Sizeable.UNITS_PERCENTAGE);
bottomLayoutBar.setSizeFull();
m_commandManager.addActionHandlers(m_topologyComponent, m_graphContainer, getMainWindow());
m_commandManager.addCommandUpdateListener(this);
menuBarUpdated(m_commandManager);
m_layout.addComponent(bottomLayoutBar, "top: 23px; left: 0px; right:0px; bottom:0px;");
m_graphContainer.redoLayout();
}
private Layout createWestLayout() {
m_tree = createTree();
final TextField filterField = new TextField("Filter");
filterField.setTextChangeTimeout(200);
Button filterBtn = new Button("Filter");
filterBtn.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
FilterableHierarchicalContainer container = (FilterableHierarchicalContainer) m_tree.getContainerDataSource();
container.removeAllContainerFilters();
String filterString = (String) filterField.getValue();
if(!filterString.equals("")) {
container.addContainerFilter(Vertex.LABEL_PROPERTY, (String) filterField.getValue(), true, false);
}
}
});
Panel scrollPanel = new Panel("Vertices");
scrollPanel.setHeight("100%");
scrollPanel.setWidth("100%");
scrollPanel.setStyleName(Reindeer.PANEL_LIGHT);
scrollPanel.addComponent(m_tree);
AbsoluteLayout absLayout = new AbsoluteLayout();
absLayout.setWidth("100%");
absLayout.setHeight("100%");
absLayout.addComponent(filterField, "top: 25px; left: 0px;");
absLayout.addComponent(filterBtn, "top: 25px; left: 135px;");
absLayout.addComponent(scrollPanel, "top: 75px; left: 0px; bottom:0px;");
return absLayout;
}
private Tree createTree() {
FilterableHierarchicalContainer container = new FilterableHierarchicalContainer(m_graphContainer.getVertexContainer());
final Tree tree = new Tree();
tree.setMultiSelect(true);
tree.setContainerDataSource(container);
tree.setImmediate(true);
tree.setItemCaptionPropertyId(Vertex.LABEL_PROPERTY);
for (Iterator<?> it = tree.rootItemIds().iterator(); it.hasNext();) {
tree.expandItemsRecursively(it.next());
}
tree.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
m_topologyComponent.selectVerticesByItemId((Collection<Object>) event.getProperty().getValue());
}
});
return tree;
}
public void updateMenuItems() {
updateMenuItems(m_menuBar.getItems());
m_menuBar.requestRepaint();
}
private void updateContextMenuItems(Object target, List<TopoContextMenuItem> items) {
for(TopoContextMenuItem contextItem : items) {
if(contextItem.hasChildren()) {
updateContextMenuItems(target, contextItem.getChildren());
} else {
m_commandManager.updateContextMenuItem(target, contextItem, m_graphContainer, getMainWindow());
}
}
}
private void updateMenuItems(List<MenuItem> menuItems) {
for(MenuItem menuItem : menuItems) {
if(menuItem.hasChildren()) {
updateMenuItems(menuItem.getChildren());
}else {
m_commandManager.updateMenuItem(menuItem, m_graphContainer, getMainWindow());
}
}
}
@Override
public void menuBarUpdated(CommandManager commandManager) {
if(m_menuBar != null) {
m_layout.removeComponent(m_menuBar);
}
if(m_contextMenu != null) {
getMainWindow().removeComponent(m_contextMenu);
}
m_menuBar = commandManager.getMenuBar(m_graphContainer, getMainWindow());
m_menuBar.setWidth("100%");
m_layout.addComponent(m_menuBar, "top: 0px; left: 0px; right:0px;");
//TODO: Finish implementing the context menu
m_contextMenu = commandManager.getContextMenu(m_graphContainer, getMainWindow());
getMainWindow().addComponent(m_contextMenu);
updateMenuItems();
}
@Override
public void show(Object target, int left, int top) {
updateContextMenuItems(target, m_contextMenu.getItems());
updateSubMenuDisplay(m_contextMenu.getItems());
m_contextMenu.setTarget(target);
m_contextMenu.show(left, top);
}
private void updateSubMenuDisplay(List<TopoContextMenuItem> items) {
for (TopoContextMenuItem item : items) {
if (!item.hasChildren()) continue;
else updateSubMenuDisplay(item.getChildren());
boolean shouldDisplay = false;
for (TopoContextMenuItem child : item.getChildren()) {
if (child.getItem().isVisible()) {
shouldDisplay = true;
break;
}
}
item.getItem().setVisible(shouldDisplay);
}
}
}
|
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletDaoTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseTransactionFailedException;
import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletDaoTransaction;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.fest.assertions.api.Assertions.*;
import static org.mockito.Mockito.*;
import static com.googlecode.catchexception.CatchException.*;
@RunWith(MockitoJUnitRunner.class)
public class ExecuteTransactionTest {
@Mock
private Database mockDatabase;
@Mock
private DatabaseTransaction mockTransaction;
@Mock
private DatabaseTable mockTable;
@Mock
private DatabaseTableRecord mockInsertRecord;
@Mock
private DatabaseTableRecord mockUpdateRecord;
private BitcoinWalletBasicWalletDaoTransaction testDaoTransaction;
@Before
public void setUpTransaction(){
when(mockDatabase.newTransaction()).thenReturn(mockTransaction);
testDaoTransaction = new BitcoinWalletBasicWalletDaoTransaction(mockDatabase);
}
@Test
public void ExecuteTransaction_OperationsExecutedSuccessFull_NoExceptions() throws Exception{
catchException(testDaoTransaction).executeTransaction(mockTable, mockInsertRecord, mockTable, mockUpdateRecord);
assertThat(caughtException()).isNull();
}
@Test
public void ExecuteTransaction_DatabaseTransactionFailedException_ThrowsCantExecuteBitconTransactionException() throws Exception{
doThrow(new DatabaseTransactionFailedException("MOCK", null,null,null)).when(mockDatabase).executeTransaction(mockTransaction);
catchException(testDaoTransaction).executeTransaction(mockTable, mockInsertRecord, mockTable, mockUpdateRecord);
}
}
|
package org.carlspring.strongbox.services.impl;
import org.carlspring.strongbox.client.ArtifactTransportException;
import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.configuration.ConfigurationManager;
import org.carlspring.strongbox.services.RepositoryManagementService;
import org.carlspring.strongbox.storage.ArtifactStorageException;
import org.carlspring.strongbox.storage.RepositoryInitializationException;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.indexing.IndexTypeEnum;
import org.carlspring.strongbox.storage.indexing.ReindexArtifactScanningListener;
import org.carlspring.strongbox.storage.indexing.RepositoryIndexManager;
import org.carlspring.strongbox.storage.indexing.RepositoryIndexer;
import org.carlspring.strongbox.storage.indexing.RepositoryIndexerFactory;
import org.carlspring.strongbox.storage.indexing.downloader.IndexDownloadRequest;
import org.carlspring.strongbox.storage.indexing.downloader.IndexDownloader;
import org.carlspring.strongbox.storage.repository.Repository;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
import org.apache.maven.index.ScanningRequest;
import org.apache.maven.index.ScanningResult;
import org.apache.maven.index.context.IndexingContext;
import org.apache.maven.index.packer.IndexPacker;
import org.apache.maven.index.packer.IndexPackingRequest;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author mtodorov
*/
@Component("repositoryManagementService")
public class RepositoryManagementServiceImpl
implements RepositoryManagementService
{
private static final Logger logger = LoggerFactory.getLogger(RepositoryManagementServiceImpl.class);
@Inject
private IndexDownloader downloader;
@Inject
private RepositoryIndexManager repositoryIndexManager;
@Inject
private RepositoryIndexerFactory repositoryIndexerFactory;
@Inject
private ConfigurationManager configurationManager;
@Inject
private IndexPacker indexPacker;
@Override
public void createRepository(String storageId,
String repositoryId)
throws IOException
{
Storage storage = getConfiguration().getStorage(storageId);
Repository repository = storage.getRepository(repositoryId);
final String storageBasedirPath = storage.getBasedir();
final File repositoryBasedir = new File(storageBasedirPath, repositoryId).getAbsoluteFile();
createRepositoryStructure(storageBasedirPath, repositoryId);
if (repository.isIndexingEnabled())
{
if (repository.isProxyRepository())
{
// Create a remote index
createRepositoryIndexer(storageId, repositoryId, IndexTypeEnum.REMOTE.getType(), repositoryBasedir);
}
// Create a local index
createRepositoryIndexer(storageId, repositoryId, IndexTypeEnum.LOCAL.getType(), repositoryBasedir);
}
}
private RepositoryIndexer createRepositoryIndexer(String storageId,
String repositoryId,
String indexType,
File repositoryBasedir)
throws RepositoryInitializationException
{
File repositoryIndexDir = new File(repositoryBasedir, ".index/" + indexType);
if (!repositoryIndexDir.exists())
{
//noinspection ResultOfMethodCallIgnored
repositoryIndexDir.mkdirs();
}
String contextId = storageId + ":" + repositoryId + ":" + indexType;
RepositoryIndexer repositoryIndexer = repositoryIndexerFactory.createRepositoryIndexer(contextId,
repositoryId,
indexType,
repositoryBasedir,
repositoryIndexDir);
repositoryIndexManager.addRepositoryIndexer(contextId, repositoryIndexer);
return repositoryIndexer;
}
@Override
public void downloadRemoteIndex(String storageId,
String repositoryId)
throws ArtifactTransportException, RepositoryInitializationException
{
Storage storage = getConfiguration().getStorage(storageId);
Repository repository = storage.getRepository(repositoryId);
File repositoryBasedir = new File(repository.getBasedir());
File remoteIndexDirectory = new File(repositoryBasedir, ".index/remote");
if (!remoteIndexDirectory.exists())
{
//noinspection ResultOfMethodCallIgnored
remoteIndexDirectory.mkdirs();
}
// Create a remote index
RepositoryIndexer repositoryIndexer = createRepositoryIndexer(storageId,
repositoryId,
IndexTypeEnum.REMOTE.getType(),
repositoryBasedir);
IndexDownloadRequest request = new IndexDownloadRequest();
request.setIndexingContextId(storageId + ":" + repositoryId + ":remote");
request.setStorageId(storageId);
request.setRepositoryId(repositoryId);
request.setRemoteRepositoryURL(repository.getRemoteRepository().getUrl());
request.setIndexLocalCacheDir(repositoryBasedir);
request.setIndexDir(remoteIndexDirectory.toString());
request.setIndexer(repositoryIndexer.getIndexer());
try
{
downloader.download(request);
}
catch (IOException | ComponentLookupException e)
{
throw new ArtifactTransportException("Failed to retrieve remote index for " +
storageId + ":" + repositoryId + "!");
}
}
private void createRepositoryStructure(String storageBasedirPath,
String repositoryId)
throws IOException
{
final File storageBasedir = new File(storageBasedirPath);
final File repositoryDir = new File(storageBasedir, repositoryId);
if (!repositoryDir.exists())
{
//noinspection ResultOfMethodCallIgnored
repositoryDir.mkdirs();
//noinspection ResultOfMethodCallIgnored
new File(repositoryDir, ".index").mkdirs();
//noinspection ResultOfMethodCallIgnored
new File(repositoryDir, ".trash").mkdirs();
}
}
@Override
public int reIndex(String storageId,
String repositoryId,
String path)
throws IOException
{
String contextId = storageId + ":" + repositoryId + ":local";
logger.info("Re-indexing " + contextId + (path != null ? ":" + path : "") + "...");
RepositoryIndexer repositoryIndexer = repositoryIndexManager.getRepositoryIndexer(contextId);
File startingPath = path != null ? new File(path) : new File(".");
IndexingContext context = repositoryIndexer.getIndexingContext();
ScanningRequest scanningRequest = new ScanningRequest(context,
new ReindexArtifactScanningListener(repositoryIndexer.getIndexer()),
startingPath.getPath());
ScanningResult scan = repositoryIndexer.getScanner()
.scan(scanningRequest);
return scan.getTotalFiles();
}
@Override
public void mergeIndexes(String sourceStorage,
String sourceRepositoryId,
String targetStorage,
String targetRepositoryId)
throws ArtifactStorageException
{
try
{
final RepositoryIndexer sourceIndex = repositoryIndexManager.getRepositoryIndexer(sourceStorage + ":" +
sourceRepositoryId +
":local");
if (sourceIndex == null)
{
throw new ArtifactStorageException("Source repository not found!");
}
final RepositoryIndexer targetIndex = repositoryIndexManager.getRepositoryIndexer(
targetStorage + ":" + targetRepositoryId + ":local");
if (targetIndex == null)
{
throw new ArtifactStorageException("Target repository not found!");
}
targetIndex.getIndexingContext().merge(FSDirectory.open(sourceIndex.getIndexDir()));
}
catch (IOException e)
{
throw new ArtifactStorageException(e.getMessage(), e);
}
}
@Override
public void pack(String storageId,
String repositoryId)
throws IOException
{
String contextId = storageId + ":" + repositoryId + ":local";
logger.info("Packing index for " + contextId + " ...");
final RepositoryIndexer indexer = repositoryIndexManager.getRepositoryIndexer(contextId);
if (indexer == null)
{
throw new NullPointerException("Unable to find RepositoryIndexer by key " + contextId +
". \nAvailable keys are " + repositoryIndexManager.getIndexes()
.keySet());
}
IndexingContext context = indexer.getIndexingContext();
final IndexSearcher indexSearcher = context.acquireIndexSearcher();
try
{
IndexPackingRequest request = new IndexPackingRequest(context,
indexSearcher.getIndexReader(),
new File(indexer.getRepositoryBasedir() + "/.index/local"));
request.setUseTargetProperties(true);
indexPacker.packIndex(request);
logger.info("Index for " + storageId + ":" + repositoryId + ":local was packed successfully.");
}
finally
{
context.releaseIndexSearcher(indexSearcher);
}
}
@Override
public void removeRepository(String storageId,
String repositoryId)
throws IOException
{
removeDirectoryStructure(storageId, repositoryId);
}
private void removeDirectoryStructure(String storageId,
String repositoryId)
throws IOException
{
Storage storage = getConfiguration().getStorage(storageId);
final String storageBasedirPath = storage.getBasedir();
final File repositoryBaseDir = new File(new File(storageBasedirPath), repositoryId);
if (repositoryBaseDir.exists())
{
FileUtils.deleteDirectory(repositoryBaseDir);
logger.debug("Removed directory structure for repository '" +
repositoryBaseDir.getAbsolutePath() + File.separatorChar + repositoryId + "'.");
}
else
{
throw new IOException("Failed to delete non-existing repository " + repositoryBaseDir.getAbsolutePath() + ".");
}
}
public Configuration getConfiguration()
{
return configurationManager.getConfiguration();
}
}
|
package org.carlspring.strongbox.controllers.configuration.security.authorization;
import org.carlspring.strongbox.authorization.dto.AuthorizationConfigDto;
import org.carlspring.strongbox.authorization.dto.RoleDto;
import org.carlspring.strongbox.authorization.service.AuthorizationConfigService;
import org.carlspring.strongbox.config.IntegrationTest;
import org.carlspring.strongbox.forms.PrivilegeForm;
import org.carlspring.strongbox.forms.PrivilegeListForm;
import org.carlspring.strongbox.forms.RoleForm;
import org.carlspring.strongbox.rest.common.RestAssuredBaseTest;
import org.carlspring.strongbox.users.domain.Privileges;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.carlspring.strongbox.controllers.configuration.security.authorization.AuthorizationConfigController.*;
import static org.hamcrest.CoreMatchers.containsString;
/**
* @author Pablo Tirado
*/
@IntegrationTest
@ExtendWith(SpringExtension.class)
public class AuthorizationConfigControllerTestIT
extends RestAssuredBaseTest
{
@Inject
private AuthorizationConfigService authorizationConfigService;
private AuthorizationConfigDto config;
@Override
@BeforeEach
public void init()
throws Exception
{
super.init();
setContextBaseUrl(getContextBaseUrl() + "/api/configuration");
config = authorizationConfigService.getDto();
}
@AfterEach
public void afterEveryTest()
{
authorizationConfigService.setAuthorizationConfig(config);
}
private void roleShouldBeAdded(String acceptHeader,
RoleForm role)
{
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.body(role)
.when()
.post(getContextBaseUrl() + "/authorization/role")
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.OK.value()) // check http status code
.body(containsString(SUCCESSFUL_ADD_ROLE));
}
@Test
public void testRoleShouldBeAddedWithResponseInJson()
{
final RoleForm customRole = new RoleForm();
customRole.setName("TEST_ROLE");
customRole.setDescription("Test role");
customRole.setRepository("Test repository");
customRole.setPrivileges(new HashSet<>(Arrays.asList(Privileges.ADMIN_LIST_REPO.name(),
Privileges.ARTIFACTS_DEPLOY.name())));
roleShouldBeAdded(MediaType.APPLICATION_JSON_VALUE, customRole);
}
@Test
public void testRoleShouldBeAddedWithResponseInText()
{
final RoleForm customRole = new RoleForm();
customRole.setName("TEST_ROLE");
customRole.setDescription("Test role");
customRole.setRepository("Test repository");
customRole.setPrivileges(new HashSet<>(Arrays.asList(Privileges.ADMIN_LIST_REPO.name(),
Privileges.ARTIFACTS_DEPLOY.name())));
roleShouldBeAdded(MediaType.TEXT_PLAIN_VALUE, customRole);
}
private void roleShouldNotBeAdded(String acceptHeader,
String roleName)
{
// prepare new role
final RoleDto customRole = new RoleDto();
customRole.setName(roleName);
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.body(customRole)
.when()
.post(getContextBaseUrl() + "/authorization/role")
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.BAD_REQUEST.value()) // check http status code
.body(containsString(FAILED_ADD_ROLE));
}
@Test
public void testExistingRoleShouldNotBeAddedWithResponseInJson()
{
String existingRoleName = config.getRoles().iterator().next().getName();
roleShouldNotBeAdded(MediaType.APPLICATION_JSON_VALUE, existingRoleName);
}
@Test
public void testExistingRoleShouldNotBeAddedWithResponseInText()
{
String existingRoleName = config.getRoles().iterator().next().getName();
roleShouldNotBeAdded(MediaType.TEXT_PLAIN_VALUE, existingRoleName);
}
@Test
public void testEmptyRoleNameShouldNotBeAddedWithResponseInJson()
{
String roleName = "";
roleShouldNotBeAdded(MediaType.APPLICATION_JSON_VALUE, roleName);
}
@Test
public void testEmptyRoleNameShouldNotBeAddedWithResponseInText()
{
String roleName = "";
roleShouldNotBeAdded(MediaType.TEXT_PLAIN_VALUE, roleName);
}
private void configXMLCouldBeDownloaded(String acceptHeader)
{
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.when()
.get(getContextBaseUrl() + "/authorization/xml")
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.OK.value()); // check http status code
}
@Test
public void testThatConfigXMLCouldBeDownloadedWithResponseInJson()
{
configXMLCouldBeDownloaded(MediaType.APPLICATION_JSON_VALUE);
}
@Test
public void testThatConfigXMLCouldBeDownloadedWithResponseInXml()
{
configXMLCouldBeDownloaded(MediaType.APPLICATION_XML_VALUE);
}
private void roleShouldBeDeleted(String acceptHeader,
String roleName)
{
// delete role
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.when()
.delete(getContextBaseUrl() + "/authorization/role/" + roleName)
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.OK.value()) // check http status code
.body(containsString(SUCCESSFUL_DELETE_ROLE));
}
@Test
public void testRoleShouldBeDeletedWithResponseInJson()
{
String roleName = config.getRoles().iterator().next().getName();
roleShouldBeDeleted(MediaType.APPLICATION_JSON_VALUE, roleName);
}
@Test
public void testRoleShouldBeDeletedWithResponseInText()
{
String roleName = config.getRoles().iterator().next().getName();
roleShouldBeDeleted(MediaType.TEXT_PLAIN_VALUE, roleName);
}
private void roleShouldNotBeDeleted(String acceptHeader,
String roleName)
{
// delete role
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.when()
.delete(getContextBaseUrl() + "/authorization/role/" + roleName)
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.BAD_REQUEST.value()) // check http status code
.body(containsString(FAILED_DELETE_ROLE));
}
@Test
public void testRoleShouldNotBeDeletedWithResponseInJson()
{
String nonExistingRoleName = "TEST_ROLE";
roleShouldNotBeDeleted(MediaType.APPLICATION_JSON_VALUE, nonExistingRoleName);
}
@Test
public void testRoleShouldNotBeDeletedWithResponseInText()
{
String nonExistingRoleName = "TEST_ROLE";
roleShouldNotBeDeleted(MediaType.TEXT_PLAIN_VALUE, nonExistingRoleName);
}
private void privilegesToAnonymousShouldBeAdded(String acceptHeader,
String privilegeName)
{
// assign privileges to anonymous user
PrivilegeListForm privilegeListForm = new PrivilegeListForm();
List<PrivilegeForm> privilegeForms = new ArrayList<>();
PrivilegeForm privilegeForm = new PrivilegeForm(privilegeName, "");
privilegeForms.add(privilegeForm);
privilegeListForm.setPrivileges(privilegeForms);
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.body(privilegeListForm)
.when()
.post(getContextBaseUrl() + "/authorization/anonymous/privileges")
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.OK.value()) // check http status code
.body(containsString(SUCCESSFUL_ASSIGN_PRIVILEGES));
}
@Test
public void testPrivilegesToAnonymousShouldBeAddedWithResponseInJson()
{
String privilegeName = Privileges.ADMIN_LIST_REPO.name();
privilegesToAnonymousShouldBeAdded(MediaType.APPLICATION_JSON_VALUE, privilegeName);
}
@Test
public void testPrivilegesToAnonymousShouldBeAddedWithResponseInText()
{
String privilegeName = Privileges.ARTIFACTS_DEPLOY.name();
privilegesToAnonymousShouldBeAdded(MediaType.TEXT_PLAIN_VALUE, privilegeName);
}
private void privilegesToAnonymousShouldNotBeAdded(String acceptHeader,
String privilegeName)
{
// assign privileges to anonymous user
PrivilegeListForm privilegeListForm = new PrivilegeListForm();
List<PrivilegeForm> privilegeForms = new ArrayList<>();
PrivilegeForm privilegeForm = new PrivilegeForm(privilegeName, "");
privilegeForms.add(privilegeForm);
privilegeListForm.setPrivileges(privilegeForms);
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.ACCEPT, acceptHeader)
.body(privilegeListForm)
.when()
.post(getContextBaseUrl() + "/authorization/anonymous/privileges")
.peek() // Use peek() to print the output
.then()
.statusCode(HttpStatus.BAD_REQUEST.value()) // check http status code
.body(containsString(FAILED_ASSIGN_PRIVILEGES));
}
@Test
public void testEmptyPrivilegeNameToAnonymousShouldNotBeAddedWithResponseInJson()
{
String privilegeName = "";
privilegesToAnonymousShouldNotBeAdded(MediaType.APPLICATION_JSON_VALUE, privilegeName);
}
@Test
public void testEmptyPrivilegeNameToAnonymousShouldNotBeAddedWithResponseInText()
{
String privilegeName = "";
privilegesToAnonymousShouldNotBeAdded(MediaType.TEXT_PLAIN_VALUE, privilegeName);
}
}
|
package org.opennms.features.topology.app.internal.operations;
import java.util.List;
import com.vaadin.ui.UI;
import org.opennms.features.topology.api.Operation;
import org.opennms.features.topology.api.OperationContext;
import org.opennms.features.topology.api.OperationContext.DisplayLocation;
import org.opennms.features.topology.api.topo.VertexRef;
import org.opennms.features.topology.app.internal.TopologyUI;
public class RedoLayoutOperation implements Operation {
@Override
public Undoer execute(List<VertexRef> targets, OperationContext operationContext) {
if (operationContext != null && operationContext.getGraphContainer() != null) {
operationContext.getGraphContainer().getBaseTopology().refresh();
operationContext.getGraphContainer().setDirty(true);
operationContext.getGraphContainer().redoLayout();
TopologyUI.getCurrent().markAsDirtyRecursive();
}
return null;
}
@Override
public boolean display(List<VertexRef> targets, OperationContext operationContext) {
return (operationContext.getDisplayLocation() == DisplayLocation.MENUBAR)
|| (targets != null && targets.size() == 0);
}
@Override
public boolean enabled(List<VertexRef> targets, OperationContext operationContext) {
return true;
}
@Override
public String getId() {
return "Refresh";
}
}
|
package org.springframework.ide.vscode.boot.java.livehover.v2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.languageserver.ProgressService;
/**
* @author Martin Lippert
*/
public class SpringProcessConnectorService {
private static final Logger log = LoggerFactory.getLogger(SpringProcessConnectorService.class);
private static final int RETRY_MAX_NO = 10;
private static final int RETRY_DELAY_IN_SECONDS = 3;
private final SpringProcessLiveDataProvider liveDataProvider;
private final ScheduledThreadPoolExecutor scheduler;
private final ConcurrentMap<String, SpringProcessConnector> connectors;
private final ConcurrentMap<String, Boolean> connectedSuccess;
private final SpringProcessConnectionChangeListener connectorListener;
private final ProgressService progressService;
public SpringProcessConnectorService(ProgressService progressService, SpringProcessLiveDataProvider liveDataProvider) {
this.liveDataProvider = liveDataProvider;
this.scheduler = new ScheduledThreadPoolExecutor(10);
this.connectors = new ConcurrentHashMap<>();
this.connectedSuccess = new ConcurrentHashMap<>();
this.progressService = progressService;
this.connectorListener = new SpringProcessConnectionChangeListener() {
@Override
public void connectionClosed(String processKey) {
disconnectProcess(processKey);
}
};
}
public void connectProcess(String processKey, SpringProcessConnector connector) {
log.info("connect to process: " + processKey);
this.connectors.put(processKey, connector);
this.connectedSuccess.put(processKey, false);
connector.addConnectorChangeListener(connectorListener);
try {
scheduleConnect(processKey, connector, 0, TimeUnit.SECONDS, 0);
}
catch (Exception e) {
log.error("error connecting to " + processKey, e);
}
}
public void refreshProcess(String processKey) {
log.info("refresh process: " + processKey);
SpringProcessConnector connector = this.connectors.get(processKey);
if (connector != null) {
scheduleRefresh(processKey, connector, 0, TimeUnit.SECONDS, 0);
}
}
public void disconnectProcess(String processKey) {
log.info("disconnect from process: " + processKey);
this.liveDataProvider.remove(processKey);
SpringProcessConnector connector = this.connectors.remove(processKey);
this.connectedSuccess.put(processKey, false);
if (connector != null) {
scheduleDisconnect(processKey, connector, 0, TimeUnit.SECONDS, 0);
}
}
public SpringProcessConnector[] getConnectedProcesses() {
return (SpringProcessConnector[]) this.connectors.values().stream()
.filter((connector) -> connectedSuccess.get(connector.getProcessKey())).toArray(SpringProcessConnector[]::new);
}
public boolean isConnected(String processKey) {
return this.connectors.containsKey(processKey);
}
/**
* common method to generate process keys from process IDs and process names
*/
public static String getProcessKey(String processID, String processName) {
return processID + " - " + processName;
}
private void scheduleConnect(String processKey, SpringProcessConnector connector, long delay, TimeUnit unit, int retryNo) {
log.info("schedule task to connect to process: " + processKey + " - retry no: " + retryNo);
this.scheduler.schedule(() -> {
try {
connector.connect();
refreshProcess(processKey);
}
catch (Exception e) {
log.info("problem occured during process connect", e);
if (retryNo < RETRY_MAX_NO) {
scheduleConnect(processKey, connector, RETRY_DELAY_IN_SECONDS, TimeUnit.SECONDS, retryNo + 1);
}
}
}, delay, unit);
}
private void scheduleDisconnect(String processKey, SpringProcessConnector connector, long delay, TimeUnit unit, int retryNo) {
log.info("schedule task to disconnect from process: " + processKey + " - retry no: " + retryNo);
this.scheduler.schedule(() -> {
try {
connector.disconnect();
}
catch (Exception e) {
log.info("problem occured during process disconnect", e);
if (retryNo < RETRY_MAX_NO) {
scheduleDisconnect(processKey, connector, RETRY_DELAY_IN_SECONDS, TimeUnit.SECONDS, retryNo + 1);
}
}
}, delay, unit);
}
private void scheduleRefresh(String processKey, SpringProcessConnector connector, long delay, TimeUnit unit, int retryNo) {
String progressMessage = "Refreshing data from Spring process: " + processKey + " - retry no: " + retryNo;
log.info(progressMessage);
this.scheduler.schedule(() -> {
// Use the same progressId to indicate with progress is done
String progressId = "spring-process-connector-service-refresh-data-"+processKey;
try {
progress(progressId, progressMessage);
SpringProcessLiveData newLiveData = connector.refresh();
if (newLiveData != null) {
if (!this.liveDataProvider.add(processKey, newLiveData)) {
this.liveDataProvider.update(processKey, newLiveData);
}
this.connectedSuccess.put(processKey, true);
}
progressDone(progressId);
}
catch (Exception e) {
log.info("problem occured during process live data refresh", e);
if (retryNo < RETRY_MAX_NO) {
scheduleRefresh(processKey, connector, RETRY_DELAY_IN_SECONDS, TimeUnit.SECONDS, retryNo + 1);
}
else {
progressDone(progressId);
disconnectProcess(processKey);
}
}
}, delay, unit);
}
private void progress(String taskId, String message) {
if (this.progressService != null) {
this.progressService.progressEvent(taskId, message);
}
}
private void progressDone(String taskId) {
if (this.progressService != null) {
this.progressService.progressDone(taskId);
}
}
}
|
package org.innovateuk.ifs.project.monitoringofficer.controller;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.project.monitoring.service.ProjectMonitoringOfficerRestService;
import org.innovateuk.ifs.project.monitoringofficer.form.MonitoringOfficerAssignProjectForm;
import org.innovateuk.ifs.project.monitoringofficer.populator.MonitoringOfficerProjectsViewModelPopulator;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.function.Supplier;
import static java.lang.String.format;
@Controller
@RequestMapping("/monitoring-officer/{monitoringOfficerId}")
@SecuredBySpring(value = "Controller",
description = "Comp Admin and Project Finance can view and assign projects to Monitoring Officers",
securedType = MonitoringOfficerController.class)
@PreAuthorize("hasAnyAuthority('comp_admin', 'project_finance')")
public class MonitoringOfficerController {
private static final String FORM_ATTR_NAME = "form";
@Autowired
private MonitoringOfficerProjectsViewModelPopulator modelPopulator;
@Autowired
private ProjectMonitoringOfficerRestService projectMonitoringOfficerRestService;
@GetMapping("/projects")
public String viewProjects(@PathVariable long monitoringOfficerId, Model model) {
model.addAttribute("model", modelPopulator.populate(monitoringOfficerId));
model.addAttribute(FORM_ATTR_NAME, new MonitoringOfficerAssignProjectForm());
return "project/monitoring-officer-projects";
}
@PostMapping("/assign")
public String assignProject(@PathVariable long monitoringOfficerId,
@Valid @ModelAttribute(FORM_ATTR_NAME) MonitoringOfficerAssignProjectForm form,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource user) {
Supplier<String> failureView = () -> {
model.addAttribute("model", modelPopulator.populate(monitoringOfficerId));
model.addAttribute(FORM_ATTR_NAME, form);
return "project/monitoring-officer-projects";
};
return validationHandler
.failNowOrSucceedWith(failureView, () -> {
RestResult<Void> result = projectMonitoringOfficerRestService.assignMonitoringOfficerToProject(monitoringOfficerId, form.getProjectId());
return validationHandler
.addAnyErrors(result)
.failNowOrSucceedWith(failureView,
() -> monitoringOfficerProjectsRedirect(monitoringOfficerId));
});
}
@GetMapping("/unassign/{projectId}")
public String unassignProject(@PathVariable long monitoringOfficerId,
@PathVariable long projectId) {
return projectMonitoringOfficerRestService
.unassignMonitoringOfficerFromProject(monitoringOfficerId, projectId)
.andOnSuccessReturn(() -> monitoringOfficerProjectsRedirect(monitoringOfficerId))
.getSuccess();
}
private static String monitoringOfficerProjectsRedirect(long monitoringOfficerId) {
return format("redirect:/monitoring-officer/%s/projects", monitoringOfficerId);
}
}
|
package fr.openwide.core.commons.util.validator;
import org.apache.commons.validator.routines.RegexValidator;
import com.google.common.base.Predicate;
import fr.openwide.core.commons.util.functional.SerializablePredicate;
/**
* An {@link RegexValidator} for phone number validation: it's very permissive but should avoid most of the errors.
*/
public class PermissivePhoneNumberValidator extends RegexValidator implements SerializablePredicate<String> {
private static final long serialVersionUID = 5254830905190414225L;
private static final PermissivePhoneNumberValidator INSTANCE = new PermissivePhoneNumberValidator();
private static final String PHONE_NUMBER_REGEX = "^\\+?[0-9 \\-\\.()]+$";
public static PermissivePhoneNumberValidator getInstance() {
return INSTANCE;
}
public PermissivePhoneNumberValidator() {
super(PHONE_NUMBER_REGEX, false);
}
/**
* @deprecated Provided only to satisfy the {@link Predicate} interface; use
* {@link #isValid(String)} instead.
*/
@Deprecated
@Override
public boolean apply(String input) {
return isValid(input);
}
}
|
package de.darwinspl.feature.graphical.configurator.composites;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import eu.hyvar.evolution.util.HyEvolutionUtil;
import eu.hyvar.dataValues.HyBooleanValue;
import eu.hyvar.dataValues.HyEnumValue;
import eu.hyvar.dataValues.HyNumberValue;
import eu.hyvar.dataValues.HyStringValue;
import eu.hyvar.dataValues.HyValue;
import eu.hyvar.evolution.HyName;
import eu.hyvar.feature.configuration.HyAttributeValueAssignment;
import eu.hyvar.feature.configuration.HyConfiguration;
import eu.hyvar.feature.configuration.HyConfigurationElement;
import eu.hyvar.feature.configuration.HyFeatureSelected;
import eu.hyvar.feature.configuration.HyVersionSelected;
public class DwSelectedConfigurationComposite extends Group {
private Text textArea;
private Button completeButton;
private Button saveConfigurationButton;
private Button deriveVariantButton;
private Button loadConfigurationButton;
public DwSelectedConfigurationComposite(Composite parent) {
super(parent, SWT.NONE);
assemble();
setText("Selected Configuration");
}
@Override
protected void checkSubclass() {
}
private void assemble() {
setLayout(new GridLayout(1, false));
textArea = new Text(this, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
textArea.setEditable(false);
textArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
completeButton = new Button(this, SWT.PUSH);
completeButton.setText("Automatically Select Versions");
completeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
saveConfigurationButton = new Button(this, SWT.PUSH);
saveConfigurationButton.setText("Save Configuration");
saveConfigurationButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
loadConfigurationButton = new Button(this, SWT.PUSH);
loadConfigurationButton.setText("Load Configuration");
loadConfigurationButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
deriveVariantButton = new Button(this, SWT.PUSH);
deriveVariantButton.setText("Derive Variant");
deriveVariantButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
}
public List<HyAttributeValueAssignment> getSelectedAttributesForFeature(HyFeatureSelected feature, HyConfiguration config){
List<HyAttributeValueAssignment> attributes = new ArrayList<>();
for(HyConfigurationElement element: config.getElements()){
if(element instanceof HyAttributeValueAssignment){
if(((HyAttributeValueAssignment) element).getAttribute().getFeature().equals(feature.getSelectedFeature())){
attributes.add((HyAttributeValueAssignment) element);
}
}
}
return attributes;
}
public List<HyVersionSelected> getSelectedVersionForFeature(HyFeatureSelected feature, HyConfiguration config){
List<HyVersionSelected> attributes = new ArrayList<>();
for(HyConfigurationElement element: config.getElements()){
if(element instanceof HyVersionSelected){
if(((HyVersionSelected) element).getSelectedVersion().getFeature().equals(feature.getSelectedFeature())){
attributes.add((HyVersionSelected) element);
}
}
}
return attributes;
}
public void setConfiguration(HyConfiguration configuration, Date date) {
String text = "";
if (configuration != null) {
for (HyConfigurationElement element : configuration.getElements()) {
if (element instanceof HyFeatureSelected) {
HyFeatureSelected select = (HyFeatureSelected) element;
HyName name = HyEvolutionUtil.getValidTemporalElement(select.getSelectedFeature().getNames(), date);
text += name.getName() + "\n";
if(!(select.getSelectedFeature().getVersions().isEmpty())){
for(HyVersionSelected versionSelected: getSelectedVersionForFeature(select, configuration)){
HyVersionSelected version = (HyVersionSelected) versionSelected;
String nameVersion = version.getSelectedVersion().getNumber();
text += "@" + nameVersion + "\n";
}
}
if (((HyFeatureSelected) element).getSelectedFeature().getAttributes().isEmpty() != true) {
for (HyAttributeValueAssignment attribute : getSelectedAttributesForFeature(select,
configuration)) {
HyAttributeValueAssignment selectAtr = (HyAttributeValueAssignment) attribute;
HyName nameAtr = HyEvolutionUtil
.getValidTemporalElement(selectAtr.getAttribute().getNames(), date);
HyValue value = selectAtr.getValue();
String stringValue;
if (value instanceof HyNumberValue) {
stringValue = Integer.toString(((HyNumberValue) value).getValue());
} else if (value instanceof HyBooleanValue) {
boolean b = ((HyBooleanValue) value).isValue();
stringValue = Boolean.toString(b);
} else if (value instanceof HyStringValue){
stringValue = ((HyStringValue) value).getValue();
}else{
stringValue = ((HyEnumValue) value).getEnumLiteral().getName();
}
text += name.getName() + "." + nameAtr.getName() + " = " + stringValue + "\n";
}
}
}
}
}
textArea.setText(text);
}
public Button getCompleteButton() {
return completeButton;
}
public Button getSaveConfigurationButton() {
return saveConfigurationButton;
}
public Button getDeriveVariantButton() {
return deriveVariantButton;
}
public Button getLoadConfigurationButton() {
return loadConfigurationButton;
}
}
|
package org.xwiki.rendering.macro.footnote;
/**
* Parameters for the {@link org.xwiki.rendering.internal.macro.footnote.FootnoteMacro} Macro. None at the moment, but
* the rendering engine requires specifying a class for parameters.
*
* @version $Id$
* @since 2.0M2
*/
public class FootnoteMacroParameters
{
}
|
package org.apache.stratos.messaging.message.processor.health.stat;
import org.apache.stratos.messaging.listener.EventListener;
import org.apache.stratos.messaging.listener.health.stat.*;
import org.apache.stratos.messaging.message.processor.MessageProcessorChain;
/**
* Defines default health stat message processor chain.
*/
public class HealthStatMessageProcessorChain extends MessageProcessorChain {
private AverageLoadAverageMessageProcessor averageLoadAverageMessageProcessor;
private AverageMemoryConsumptionMessageProcessor averageMemoryConsumptionMessageProcessor;
private AverageRequestsInFlightMessageProcessor averageRequestsInFlightMessageProcessor;
private GradientOfLoadAverageMessageProcessor gradientOfLoadAverageMessageProcessor;
private GradientOfMemoryConsumptionMessageProcessor gradientOfMemoryConsumptionMessageProcessor;
private GradientOfRequestsInFlightMessageProcessor gradientOfRequestsInFlightMessageProcessor;
private SecondDerivativeOfLoadAverageMessageProcessor secondDerivativeOfLoadAverageMessageProcessor;
private SecondDerivativeOfMemoryConsumptionMessageProcessor secondDerivativeOfMemoryConsumptionMessageProcessor;
private SecondDerivativeOfRequestsInFlightMessageProcessor secondDerivativeOfRequestsInFlightMessageProcessor;
private MemberAverageLoadAverageMessageProcessor memberAverageLoadAverageMessageProcessor;
private MemberAverageMemoryConsumptionMessageProcessor memberAverageMemoryConsumptionMessageProcessor;
private MemberGradientOfLoadAverageMessageProcessor memberGradientOfLoadAverageMessageProcessor;
private MemberGradientOfMemoryConsumptionMessageProcessor memberGradientOfMemoryConsumptionMessageProcessor;
private MemberSecondDerivativeOfLoadAverageMessageProcessor memberSecondDerivativeOfLoadAverageMessageProcessor;
private MemberSecondDerivativeOfMemoryConsumptionMessageProcessor memberSecondDerivativeOfMemoryConsumptionMessageProcessor;
private MemberFaultMessageProcessor memberFaultMessageProcessor;
protected void initialize() {
//Most frequent first order is defined in default
memberAverageLoadAverageMessageProcessor = new MemberAverageLoadAverageMessageProcessor();
add(memberAverageLoadAverageMessageProcessor);
memberGradientOfLoadAverageMessageProcessor = new MemberGradientOfLoadAverageMessageProcessor();
add(memberGradientOfLoadAverageMessageProcessor);
memberSecondDerivativeOfLoadAverageMessageProcessor = new MemberSecondDerivativeOfLoadAverageMessageProcessor();
add(memberSecondDerivativeOfLoadAverageMessageProcessor);
memberAverageMemoryConsumptionMessageProcessor = new MemberAverageMemoryConsumptionMessageProcessor();
add(memberAverageMemoryConsumptionMessageProcessor);
memberGradientOfMemoryConsumptionMessageProcessor = new MemberGradientOfMemoryConsumptionMessageProcessor();
add(memberGradientOfMemoryConsumptionMessageProcessor);
memberSecondDerivativeOfMemoryConsumptionMessageProcessor = new MemberSecondDerivativeOfMemoryConsumptionMessageProcessor();
add(memberSecondDerivativeOfMemoryConsumptionMessageProcessor);
averageRequestsInFlightMessageProcessor = new AverageRequestsInFlightMessageProcessor();
add(averageRequestsInFlightMessageProcessor);
gradientOfRequestsInFlightMessageProcessor = new GradientOfRequestsInFlightMessageProcessor();
add(gradientOfRequestsInFlightMessageProcessor);
secondDerivativeOfRequestsInFlightMessageProcessor = new SecondDerivativeOfRequestsInFlightMessageProcessor();
add(secondDerivativeOfRequestsInFlightMessageProcessor);
averageLoadAverageMessageProcessor = new AverageLoadAverageMessageProcessor();
add(averageLoadAverageMessageProcessor);
gradientOfLoadAverageMessageProcessor = new GradientOfLoadAverageMessageProcessor();
add(gradientOfLoadAverageMessageProcessor);
secondDerivativeOfLoadAverageMessageProcessor = new SecondDerivativeOfLoadAverageMessageProcessor();
add(secondDerivativeOfLoadAverageMessageProcessor);
averageMemoryConsumptionMessageProcessor = new AverageMemoryConsumptionMessageProcessor();
add(averageMemoryConsumptionMessageProcessor);
gradientOfMemoryConsumptionMessageProcessor = new GradientOfMemoryConsumptionMessageProcessor();
add(gradientOfMemoryConsumptionMessageProcessor);
secondDerivativeOfMemoryConsumptionMessageProcessor = new SecondDerivativeOfMemoryConsumptionMessageProcessor();
add(secondDerivativeOfMemoryConsumptionMessageProcessor);
memberFaultMessageProcessor = new MemberFaultMessageProcessor();
add(memberFaultMessageProcessor);
}
public void addEventListener(EventListener eventListener) {
if (eventListener instanceof AverageLoadAverageEventListener) {
averageLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof AverageMemoryConsumptionEventListener) {
averageMemoryConsumptionMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof AverageRequestsInFlightEventListener) {
averageRequestsInFlightMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof GradientOfLoadAverageEventListener) {
gradientOfLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof GradientOfMemoryConsumptionEventListener) {
gradientOfMemoryConsumptionMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof GradientOfRequestsInFlightEventListener) {
gradientOfRequestsInFlightMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberAverageLoadAverageEventListener) {
memberAverageLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberAverageMemoryConsumptionEventListener) {
memberAverageMemoryConsumptionMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberFaultEventListener) {
memberFaultMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberGradientOfLoadAverageEventListener) {
memberGradientOfLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberGradientOfMemoryConsumptionEventListener) {
memberGradientOfMemoryConsumptionMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberSecondDerivativeOfLoadAverageEventListener) {
memberSecondDerivativeOfLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof MemberSecondDerivativeOfMemoryConsumptionEventListener) {
memberSecondDerivativeOfMemoryConsumptionMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof SecondDerivativeOfLoadAverageEventListener) {
secondDerivativeOfLoadAverageMessageProcessor.addEventListener(eventListener);
} else if (eventListener instanceof SecondDerivativeOfMemoryConsumptionEventListener) {
secondDerivativeOfMemoryConsumptionMessageProcessor.addEventListener(eventListener);
}else if (eventListener instanceof SecondDerivativeOfRequestsInFlightEventListener) {
secondDerivativeOfRequestsInFlightMessageProcessor.addEventListener(eventListener);
}
else {
throw new RuntimeException("Unknown event listener");
}
}
}
|
package demo;
import demo.HandGui;
import demo.Fallen.SimpleColorTableModel;
import demo.DeckGui;
import demo.CardGui;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import data.LoadData;
import javax.swing.border.BevelBorder;
import javax.swing.UIManager;
import javax.swing.border.MatteBorder;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.swing.SwingConstants;
import javax.swing.JSlider;
import java.awt.Canvas;
import javax.swing.border.EtchedBorder;
import javax.swing.JTextPane;
import java.awt.Rectangle;
import javax.swing.JLayeredPane;
public class PlayerGui extends JLayeredPane implements ActionListener, MouseListener {
public Barriers barriers;
public Drained powers;
public static DeckGui deck;
public HandGui hand;
public fieldGui field;
public AIGui ai;
int turn;
int acampo=-1;
int i=0;
private Fallen fallen ;
private LoadData cartas;
JInternalFrame pane;
private Phases phases;
public JButton changePhase;
public PlayerGui(int x , int y, String name) throws IOException {
setBorder(null);
setBackground(UIManager.getColor("Button.disabledShadow"));
hand= new HandGui (0,0);
hand.setLocation(179, 510);
hand.addMouseListener(this);
setOpaque(false);
setLayout(null);
setBounds(x,y, 1024, 768);
JLabel name_1 = new JLabel("Player : "+ name);
add(name_1);
name_1.setForeground(new Color(255, 248, 220));
name_1.setBackground(Color.WHITE);
name_1.setHorizontalAlignment(SwingConstants.CENTER);
name_1.setFont(new Font("Showcard Gothic", Font.BOLD | Font.ITALIC, 11));
name_1.setBounds(780, 450, 176, 64);
pane = new JInternalFrame("THE FALLEN");
phases=new Phases(200,290);
add(phases);
this.add(hand);
field = new fieldGui(220,350);
ai = new AIGui();
field.addMouseListener(this);
this.add(field);
add(ai);
powers=new Drained(15,320);
add(powers);
deck = new DeckGui(0,0);
deck.setSize(250, 343);
deck.setLocation(770, 361);
this.add(deck);
deck.btnNewButton.addActionListener(this);
deck.btnNewButton_1.addActionListener(this);
barriers =new Barriers(179,500);
add(barriers);
barriers.addMouseListener(this);
for(int i=1;i<=5;i++)
{
int pos= hand.draw(deck.Deck.extraerR());
hand.handgui[pos-1].addMouseListener(this);
deck.textField.setText("cards left "+ deck.Deck.cardsLeft());
deck.textField.repaint();
repaint();
}
for (int i=0;i<5;i++)
barriers.barriers[i].addMouseListener(this);
fallen=new Fallen();
add(fallen);
juego();
}
//este sera nuestro manejador de juego, aca estara todas las condiciones y cosas de las phases
public void juego()
{
this.changePhase = new JButton("cambiar");
this.changePhase.setBounds(450, 80, 90, 20);
this.changePhase.setVisible(true);
this.add(this.changePhase);
this.changePhase.addActionListener(this);
/*
* por defecto se desabilitaran todos los eventos del clic del juego y acciones
* (esto esta pensado sin la integracion del modulo de eventos, eso se agrega aca en las phases necesarias y ya)
*
* lo que se puede hacer en el juego es lo siguiente
* sacar card a barrier
* sacar card a hand
* colocar cartas
* atacar
* pasar de turno
*
* en cada phase se ira habilitando cada una de estas funcionalidades, para que el jugagor disponga de ellas
*
* y esta secuencia de phases se elaborara en un cliclo infinito hasta que uno o los dos players
* tengan una lp <= 0
* */
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==deck.btnNewButton_1)
{
fallen.setVisible(true);
moveToFront(fallen);
}
if(e.getSource()==changePhase){
if(phases.actual<5)
phases.change(phases.actual+1);
else
phases.change(0);
repaint();
}
}
public class CirclePanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
g.drawOval(0, 0, g.getClipBounds().width, g.getClipBounds().height);
}
}
public DeckGui getDeck() {
return deck;
}
public void mouseClicked(MouseEvent e)
{
int where;
if(e.getButton() == MouseEvent.BUTTON1)
{if(e.getClickCount()==1)
{
if(e.getSource()==barriers.barriers[0])
{
int pos= hand.draw(barriers.cards[0]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(0);
repaint();
}
if(e.getSource()==barriers.barriers[1])
{
int pos= hand.draw(barriers.cards[1]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(1);
repaint();
}
if(e.getSource()==barriers.barriers[2])
{
int pos= hand.draw(barriers.cards[2]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(2);
repaint();
}
if(e.getSource()==barriers.barriers[3])
{
int pos= hand.draw(barriers.cards[3]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(3);
repaint();
}
if(e.getSource()==barriers.barriers[4])
{
int pos= hand.draw(barriers.cards[4]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(4);
repaint();
}
}
if(e.getClickCount()==2)
{
if(e.getSource()==hand.handgui[0])
{
acampo=0;
}
else if(e.getSource()==hand.handgui[1])
{
acampo=1;
}
else if(e.getSource()==hand.handgui[2])
{
acampo=2;
}
else if(e.getSource()==hand.handgui[3])
{
acampo=3;
}else if(e.getSource()==hand.handgui[4])
{
acampo=4;
}
if(acampo!=-1)
{
where=field.findwhere();
if(where!=-1)
{
hand.discard(acampo+1);
SmallCard carta;
Reverse volteada;
try {
Random randomGenerator = new Random();
int test=randomGenerator.nextInt(10);
if(test % 2==0)
{
carta = new SmallCard(true,hand.handgui[acampo].getcard());
volteada=new Reverse(true,hand.handgui[acampo].getcard());
}else{
carta = new SmallCard(false,hand.handgui[acampo].getcard());
volteada=new Reverse(false,hand.handgui[acampo].getcard());
}
carta.addMouseListener(this);
volteada.addMouseListener(this);
field.poner(carta,where);
ai.aifield.poner(volteada, where);
repaint();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
acampo=-1;
}
}
}
}
else if(e.getButton() == MouseEvent.BUTTON3)
{
if(e.getClickCount()==1)
{
if(e.getSource()==hand.handgui[0])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[0]);
hand.discard(1);
}
if(e.getSource()==hand.handgui[1])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[1]);
hand.discard(2);
}
if(e.getSource()==hand.handgui[2])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[2]);
hand.discard(3);
}
if(e.getSource()==hand.handgui[3])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[3]);
hand.discard(4);
}
if(e.getSource()==hand.handgui[4])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[4]);
hand.discard(5);
}
if(e.getSource()==field.cards[0])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[0].getcard());
field.quitar(0);
}
if(e.getSource()==field.cards[1])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[1].getcard());
field.quitar(1);
}
if(e.getSource()==field.cards[2])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[2].getcard());
field.quitar(2);
}
if(e.getSource()==field.cards[3])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[3].getcard());
field.quitar(3);
}if(e.getSource()==field.cards[4])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[4].getcard());
field.quitar(4);
}
}
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseExited(MouseEvent e) {
if(e.getSource()==hand.handgui[0])
{
hand.handgui[0].setBounds(0, 20, 124, 186);
}
else if(e.getSource()==hand.handgui[1])
{
hand.handgui[1].setBounds(124, 20, 124, 186);
}
else if(e.getSource()==hand.handgui[2])
{
hand.handgui[2].setBounds(248, 20, 124, 186);
}
else if(e.getSource()==hand.handgui[3])
{
hand.handgui[3].setBounds(372, 20, 124, 186);
}else if(e.getSource()==hand.handgui[4])
{
hand.handgui[4].setBounds(496, 20, 124, 186);
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e)
{
if(e.getSource()==hand.handgui[0])
{
hand.handgui[0].setBounds(0, 0, 124, 186);
}
else if(e.getSource()==hand.handgui[1])
{
hand.handgui[1].setBounds(124, 0, 124, 186);
}
else if(e.getSource()==hand.handgui[2])
{
hand.handgui[2].setBounds(248, 0, 124, 186);
}
else if(e.getSource()==hand.handgui[3])
{
hand.handgui[3].setBounds(372, 0, 124, 186);
}else if(e.getSource()==hand.handgui[4])
{
hand.handgui[4].setBounds(496, 0, 124, 186);
}
}
}
|
package fr.openwide.core.jpa.more.business.search.query;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.transaction.annotation.Transactional;
import com.querydsl.core.QueryModifiers;
import com.querydsl.core.types.CollectionExpression;
import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.CollectionPath;
import com.querydsl.core.types.dsl.ComparableExpression;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.impl.JPAQuery;
import fr.openwide.core.jpa.more.business.sort.ISort;
import fr.openwide.core.jpa.more.business.sort.SortUtils;
public abstract class AbstractJpaSearchQuery<T, S extends ISort<OrderSpecifier<?>>> extends AbstractSearchQuery<T, S> /* NOT Serializable */ {
private final EntityPath<T> entityPath;
private JPAQuery<T> jpaQuery;
private JPAQuery<T> finalJpaQuery;
@SafeVarargs
protected AbstractJpaSearchQuery(EntityPath<T> entityPath, S ... defaultSorts) {
super(defaultSorts);
this.entityPath = entityPath;
}
@PostConstruct
private void init() {
jpaQuery = new JPAQuery<T>(entityManager)
.select(entityPath)
.from(entityPath);
}
public <P> void innerJoin(CollectionExpression<?,P> target, Path<P> alias) {
jpaQuery.innerJoin(target, alias);
}
// Junction appender
// > Must
protected void must(BooleanExpression booleanExpression) {
if (booleanExpression != null) {
jpaQuery.where(booleanExpression);
}
}
protected void mustIfNotNull(JPAQuery<T> jpaQuery, BooleanExpression ... booleanExpressions) {
for (BooleanExpression booleanExpression : booleanExpressions) {
if (booleanExpression != null) {
jpaQuery.where(booleanExpression);
}
}
}
// > Should
protected void shouldIfNotNull(BooleanExpression ... booleanExpressions) {
BooleanExpression condition = null;
for (BooleanExpression booleanExpression : booleanExpressions) {
if (condition == null) {
condition = booleanExpression;
} else {
condition = condition.or(booleanExpression);
}
}
if (condition != null) {
jpaQuery.where(condition);
}
}
// List and count
/**
* Allow to add filter before generating the full text query.<br />
* Sample:
* <ul>
* <li>must(matchIfGiven(qCompany.manager.organization, organization))</li>
* <li>must(matchIfGiven(qCompany.status, CompanyStatus.ACTIVE))</li>
* </ul>
*/
protected void addFilterBeforeFinalizeQuery() {
// Nothing
}
private JPAQuery<T> getFinalQuery() {
if (finalJpaQuery == null) {
addFilterBeforeFinalizeQuery();
for (OrderSpecifier<?> orderSpecifier : SortUtils.getOrderSpecifierWithDefaults(sortMap, defaultSorts)) {
jpaQuery.orderBy(orderSpecifier);
}
finalJpaQuery = jpaQuery;
}
return finalJpaQuery;
}
@Override
@Transactional(readOnly = true)
public final List<T> fullList() {
return getQueryList(null, null).fetch();
}
@Override
@Transactional(readOnly = true)
public final List<T> list(long offset, long limit) {
return getQueryList(offset, limit).fetch();
}
protected JPAQuery<T> getQueryList(Long offset, Long limit) {
JPAQuery<T> finalQuery = getFinalQuery();
// Handle multiple calls to getQueryList()
finalQuery.restrict(QueryModifiers.EMPTY);
if (offset != null) {
finalQuery.offset(offset);
}
if (limit != null) {
finalQuery.limit(limit);
}
return finalQuery;
}
@Override
@Transactional(readOnly = true)
public long count() {
return getFinalQuery().fetchCount();
}
// Query factory
// > Match if given
protected <P extends Comparable<?>> BooleanExpression matchIfGiven(SimpleExpression<P> simpleExpression, P value) {
if (value != null) {
return simpleExpression.eq(value);
}
return null;
}
// > Contains if given
protected <E, Q extends SimpleExpression<? super E>> BooleanExpression containsIfGiven(CollectionPath<E, Q> collectionPath, E value) {
if (value != null) {
return collectionPath.contains(value);
}
return null;
}
// > Match one if given
protected <P extends Comparable<?>> BooleanExpression matchOneIfGiven(SimpleExpression<P> simpleExpression, Collection<? extends P> possibleValues) {
if (possibleValues != null && !possibleValues.isEmpty()) {
return simpleExpression.in(possibleValues);
}
return null;
}
// > Match all if given
protected <P extends Comparable<?>> BooleanExpression matchAllIfGiven(SimpleExpression<P> simpleExpression, Collection<? extends P> possibleValues) {
if (possibleValues != null && !possibleValues.isEmpty()) {
BooleanExpression rootExpression = null;
for (P possibleValue : possibleValues) {
if (rootExpression == null) {
rootExpression = simpleExpression.eq(possibleValue);
} else {
rootExpression = rootExpression.and(simpleExpression.eq(possibleValue));
}
}
return rootExpression;
}
return null;
}
// > Match range if given
protected <P extends Comparable<?>> BooleanExpression matchRangeIfGiven(ComparableExpression<P> comparableExpression, P minValue, P maxValue) {
if (minValue != null && maxValue != null) {
return comparableExpression.between(minValue, maxValue);
} else if (minValue != null) {
return comparableExpression.goe(minValue);
} else if (maxValue != null) {
return comparableExpression.loe(maxValue);
}
return null;
}
protected <P extends Comparable<?>> BooleanExpression matchExclusiveRangeIfGiven(ComparableExpression<P> comparableExpression, P minValue, P maxValue) {
if (minValue != null && maxValue != null) {
return comparableExpression.gt(minValue).and(comparableExpression.lt(maxValue));
} else if (minValue != null) {
return comparableExpression.gt(minValue);
} else if (maxValue != null) {
return comparableExpression.lt(maxValue);
}
return null;
}
}
|
package admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.User;
import dao.UserDAOImpl;
/**
* Servlet implementation class CreateUser
* urlPatterns={"/CreatePostServlet", "/DeletePost"}
*/
@WebServlet(urlPatterns={"/admin/CreateUser","/admin/DeleteUser"})
public class CreateUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CreateUser() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equals("delete") && request.getParameter("userId") !=null){
String userId = request.getParameter("userId");
int id = Integer.parseInt(userId);
UserDAOImpl udao = new UserDAOImpl();
udao.deleteById(id);
}
response.sendRedirect("UserList");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection = null;
String username = request.getParameter("username");
String xxxyyyzzz = request.getParameter("password");
String role = request.getParameter("role");
User user = new User();
user.setPassword(xxxyyyzzz);
user.setUserName(username);
user.setUserRole(role);
UserDAOImpl udao = new UserDAOImpl();
udao.insertUser(user);
response.sendRedirect("UserList");
}
}
|
package alda;
import com.google.gson.Gson;
import org.zeromq.ZContext;
import org.zeromq.ZMsg;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.PollItem;
import org.zeromq.ZMQ.Poller;
import org.zeromq.ZMQ.Socket;
public class AldaRequest {
private static ZContext zContext = null;
public static ZContext getZContext() {
if (zContext == null) {
zContext = new ZContext();
}
return zContext;
}
private Socket getDealerSocket() {
return getZContext().createSocket(ZMQ.DEALER);
}
private final static int REQUEST_TIMEOUT = 2500;
private final static int REQUEST_RETRIES = 3; // Before we abandon
private transient String host;
private transient int port;
public transient byte[] workerToUse;
public AldaRequest(String host, int port) {
this.host = host;
this.port = port;
}
public String command;
public String body;
public AldaRequestOptions options;
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
private AldaResponse sendRequest(String req, ZContext ctx, Socket client, int timeout, int retries)
throws NoResponseException {
if (retries < 0 || Thread.currentThread().isInterrupted()) {
throw new NoResponseException("Alda server is down. To start the server, run `alda up`.");
}
assert (client != null);
client.connect(this.host + ":" + this.port);
ZMsg msg = new ZMsg();
msg.addString(this.toJson());
if (this.workerToUse != null) {
msg.add(this.workerToUse);
}
msg.addString(this.command);
msg.send(client);
PollItem items[] = {new PollItem(client, Poller.POLLIN)};
int rc = ZMQ.poll(items, timeout);
if (rc == -1) {
throw new NoResponseException("Connection interrupted.");
}
if (items[0].isReadable()) {
String address = client.recvStr();
if (address == null) {
throw new NoResponseException("Connection interrupted.");
}
String responseJson = client.recvStr();
if (responseJson == null) {
throw new NoResponseException("Connection interrupted.");
}
AldaResponse response = AldaResponse.fromJson(responseJson);
if (!response.noWorker) {
byte[] workerAddress = client.recv(ZMQ.DONTWAIT);
if (workerAddress != null) {
response.workerAddress = workerAddress;
}
}
return response;
}
// Send request again until we're out of retries
return sendRequest(req, ctx, client, timeout, retries - 1);
}
private AldaResponse sendRequest(String req, ZContext ctx, Socket client,
int timeout)
throws NoResponseException {
return sendRequest(req, ctx, client, timeout, REQUEST_RETRIES);
}
private AldaResponse sendRequest(String req, ZContext ctx, Socket client)
throws NoResponseException {
return sendRequest(req, ctx, client, REQUEST_TIMEOUT, REQUEST_RETRIES);
}
public AldaResponse send(int timeout, int retries)
throws NoResponseException {
ZContext ctx = getZContext();
Socket client = getDealerSocket();
return sendRequest(this.toJson(), ctx, client, timeout, retries);
}
public AldaResponse send(int timeout) throws NoResponseException {
return send(timeout, REQUEST_RETRIES);
}
public AldaResponse send() throws NoResponseException {
return send(REQUEST_TIMEOUT, REQUEST_RETRIES);
}
}
|
package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.TextView;
public class FWTextView extends TextView implements NativeCommandHandler {
private FrameWork frame;
ViewStyleManager normalStyle, activeStyle, currentStyle, linkStyle;
public FWTextView(final FrameWork frame, boolean autolink) {
super(frame);
this.frame = frame;
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
this.linkStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
this.setClickable(false);
this.setFocusable(false);
if (autolink) {
this.setLinksClickable(true);
this.setAutoLinkMask(15);
}
}
@Override
public void addChild(View view) { }
@Override
public void addOption(int optionId, String text) { }
@Override
public void setValue(String v) {
setText(v);
}
@Override
public void setValue(int v) { }
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
if (normalStyle == currentStyle) normalStyle.apply(this);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
if (activeStyle == currentStyle) activeStyle.apply(this);
} else if (selector == Selector.LINK) {
linkStyle.setStyle(key, value);
linkStyle.applyLinkColor(this);
}
if (key.equals("max-lines")) {
setMaxLines(Integer.parseInt(value));
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public int getElementId() {
return getId();
}
@Override
public void onScreenOrientationChange(boolean isLandscape) { }
@Override
public void addData(String text, int row, int column, int sheet) { }
@Override
public void setViewVisibility(boolean visibility) {
if (visibility){
this.setVisibility(VISIBLE);
} else {
this.setVisibility(INVISIBLE);
}
}
@Override
public void clear() { }
@Override
public void flush() { }
@Override
public void addColumn(String text, int columnType) { }
@Override
public void reshape(int value, int size) { }
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) { }
@Override
public void deinitialize() { }
@Override
public void addImageUrl(String url, int width, int height) { }
}
|
package com.sims.topaz;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.sims.topaz.adapter.PreviewListAdapter;
import com.sims.topaz.network.modele.Preview;
import com.sims.topaz.utils.DebugUtils;
/**
* A fragment representing a list of Items.
* <p />
* Large screen devices (such as tablets) are supported by replacing the
* ListView with a GridView.
* <p />
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*/
public class PreviewListFragment extends Fragment implements
AbsListView.OnItemClickListener {
private List<Preview> previews;
private OnPreviewClickListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
public static PreviewListFragment newInstance(List<Preview> param1) {
PreviewListFragment fragment = new PreviewListFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
fragment.setPreviews(param1);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PreviewListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(previews==null) DebugUtils.logException(
new Exception("preview list is null"));
mAdapter = new PreviewListAdapter(getActivity(),
R.layout.adapter_preview_item,
previews);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_preview, container,
false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnPreviewClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener
.onPreviewClick(previews.get(position));
}
}
public void setPreviews(List<Preview> previews) {
this.previews = previews;
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyText instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnPreviewClickListener {
public void onPreviewClick(Preview preview);
}
}
|
package io.jchat.android.utils;
import android.text.TextUtils;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.google.gson.jpush.JsonElement;
import com.google.gson.jpush.JsonObject;
import com.google.gson.jpush.JsonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.FileContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.LocationContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.content.VoiceContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.enums.MessageDirect;
import cn.jpush.im.android.api.model.ChatRoomInfo;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import io.jchat.android.Constant;
public class ResultUtils {
public static Map<String, String> fromMap(ReadableMap extras) {
Map<String, String> map = new HashMap<String, String>();
ReadableMapKeySetIterator keysItr = extras.keySetIterator();
while (keysItr.hasNextKey()) {
String key = keysItr.nextKey();
String value = extras.getString(key);
map.put(key, value);
}
return map;
}
public static WritableMap toJSObject(Map<String, String> map) {
Iterator<String> iterator = map.keySet().iterator();
WritableMap object = Arguments.createMap();
while (iterator.hasNext()) {
String key = iterator.next();
object.putString(key, map.get(key));
}
return object;
}
public static WritableMap toJSObject(final UserInfo userInfo) {
if (userInfo == null) {
return Arguments.createMap();
}
final WritableMap result = Arguments.createMap();
result.putString(Constant.TYPE, Constant.TYPE_USER);
if (null != userInfo.getGender()) {
result.putString(Constant.GENDER, userInfo.getGender().toString());
} else {
result.putString(Constant.GENDER, "unknown");
}
result.putString(Constant.USERNAME, userInfo.getUserName());
result.putString(Constant.APP_KEY, userInfo.getAppKey());
result.putString(Constant.NICKNAME, userInfo.getNickname());
if (userInfo.getAvatarFile() != null) {
result.putString(Constant.AVATAR_THUMB_PATH, userInfo.getAvatarFile().getAbsolutePath());
} else {
result.putString("avatarThumbPath", "");
}
if (userInfo.getExtras() != null && userInfo.getExtras().size() > 0) {
result.putMap(Constant.EXTRAS, toJSObject(userInfo.getExtras()));
}
result.putDouble(Constant.BIRTHDAY, userInfo.getBirthday());
result.putString(Constant.REGION, userInfo.getRegion());
result.putString(Constant.SIGNATURE, userInfo.getSignature());
result.putString(Constant.ADDRESS, userInfo.getAddress());
result.putString(Constant.NOTE_NAME, userInfo.getNotename());
result.putString(Constant.NOTE_TEXT, userInfo.getNoteText());
result.putBoolean(Constant.IS_NO_DISTURB, userInfo.getNoDisturb() == 1);
result.putBoolean(Constant.IS_IN_BLACKLIST, userInfo.getBlacklist() == 1);
result.putBoolean(Constant.IS_FRIEND, userInfo.isFriend());
return result;
}
public static WritableMap toJSObject(GroupInfo groupInfo) {
WritableMap result = Arguments.createMap();
result.putString(Constant.TYPE, Constant.TYPE_GROUP);
result.putString(Constant.ID, String.valueOf(groupInfo.getGroupID()));
result.putString(Constant.NAME, groupInfo.getGroupName());
result.putString(Constant.DESC, groupInfo.getGroupDescription());
result.putInt(Constant.LEVEL, groupInfo.getGroupLevel());
result.putString(Constant.OWNER, groupInfo.getGroupOwner());
result.putString(Constant.OWNER_APP_KEY, groupInfo.getOwnerAppkey());
result.putInt(Constant.MAX_MEMBER_COUNT, groupInfo.getMaxMemberCount());
result.putBoolean(Constant.IS_NO_DISTURB, groupInfo.getNoDisturb() == 1);
result.putBoolean(Constant.IS_BLOCKED, groupInfo.isGroupBlocked() == 1);
return result;
}
public static WritableMap toJSObject(Message msg) {
WritableMap result = Arguments.createMap();
try {
result.putString(Constant.ID, String.valueOf(msg.getId()));
result.putString(Constant.SERVER_ID, String.valueOf(msg.getServerMessageId()));
result.putMap(Constant.FROM, toJSObject(msg.getFromUser()));
if (msg.getDirect() == MessageDirect.send) {
if (msg.getTargetType() == ConversationType.single) {
result.putMap(Constant.TARGET, toJSObject((UserInfo) msg.getTargetInfo()));
} else if (msg.getTargetType() == ConversationType.group) {
result.putMap(Constant.TARGET, toJSObject((GroupInfo) msg.getTargetInfo()));
}
} else {
UserInfo myInfo = JMessageClient.getMyInfo();
result.putMap(Constant.TARGET, toJSObject(myInfo));
}
MessageContent content = msg.getContent();
if (content.getStringExtras() != null) {
result.putMap(Constant.EXTRAS, toJSObject(content.getStringExtras()));
}
result.putDouble(Constant.CREATE_TIME, msg.getCreateTime());
result.putInt(Constant.UNRECEIPT_COUNT, msg.getUnreceiptCnt());
switch (msg.getContentType()) {
case text:
result.putString(Constant.TYPE, Constant.TEXT);
result.putString(Constant.TEXT, ((TextContent) content).getText());
break;
case image:
result.putString(Constant.TYPE, Constant.IMAGE);
ImageContent imageContent = (ImageContent) content;
result.putString(Constant.THUMB_PATH, imageContent.getLocalThumbnailPath() + "." + imageContent.getFormat());
break;
case voice:
result.putString(Constant.TYPE, Constant.VOICE);
VoiceContent voiceContent = (VoiceContent) content;
result.putString(Constant.PATH, voiceContent.getLocalPath() + "." + voiceContent.getFormat());
result.putInt(Constant.DURATION, ((VoiceContent) content).getDuration());
break;
case file:
result.putString(Constant.TYPE, Constant.FILE);
FileContent fileContent = (FileContent) content;
result.putString(Constant.FILE_NAME, fileContent.getFileName() + "." + fileContent.getFormat());
break;
case custom:
result.putString(Constant.TYPE, Constant.CUSTOM);
Map<String, String> customObject = ((CustomContent) content).getAllStringValues();
result.putMap(Constant.CUSTOM_OBJECT, toJSObject(customObject));
break;
case location:
result.putString(Constant.TYPE, Constant.LOCATION);
result.putDouble(Constant.LATITUDE, ((LocationContent) content).getLatitude().doubleValue());
result.putDouble(Constant.LONGITUDE, ((LocationContent) content).getLongitude().doubleValue());
result.putString(Constant.ADDRESS, ((LocationContent) content).getAddress());
result.putDouble(Constant.SCALE, ((LocationContent) content).getScale().doubleValue());
break;
case eventNotification:
result.putString(Constant.TYPE, "event");
List usernameList = ((EventNotificationContent) content).getUserNames();
result.putArray(Constant.USERNAMES, toJSArray(usernameList));
switch (((EventNotificationContent) content).getEventNotificationType()) {
case group_member_added:
result.putString(Constant.EVENT_TYPE, "group_member_added");
break;
case group_member_removed:
result.putString(Constant.EVENT_TYPE, "group_member_removed");
break;
case group_member_exit:
result.putString(Constant.EVENT_TYPE, "group_member_exit");
break;
}
default:
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static WritableMap toJSObject(Conversation conversation) {
WritableMap map = Arguments.createMap();
try {
map.putString(Constant.TITLE, conversation.getTitle());
map.putString(Constant.CONVERSATION_TYPE, conversation.getType().name());
map.putInt(Constant.UNREAD_COUNT, conversation.getUnReadMsgCnt());
if (conversation.getLatestMessage() != null) {
map.putMap(Constant.LATEST_MESSAGE, toJSObject(conversation.getLatestMessage()));
}
if (!TextUtils.isEmpty(conversation.getExtra())) {
WritableMap extrasMap = Arguments.createMap();
String extras = conversation.getExtra();
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(extras).getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
extrasMap.putString(entry.getKey(), entry.getValue().toString());
}
map.putMap(Constant.EXTRAS, extrasMap);
}
if (conversation.getType() == ConversationType.single) {
UserInfo targetInfo = (UserInfo) conversation.getTargetInfo();
map.putMap(Constant.TARGET, toJSObject(targetInfo));
} else if (conversation.getType() == ConversationType.group) {
GroupInfo targetInfo = (GroupInfo) conversation.getTargetInfo();
map.putMap(Constant.TARGET, toJSObject(targetInfo));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static WritableMap toJSObject(ChatRoomInfo chatRoomInfo, final Callback fail) {
final WritableMap map = Arguments.createMap();
try {
map.putString(Constant.ROOM_ID, String.valueOf(chatRoomInfo.getRoomID()));
map.putString(Constant.ROOM_NAME, chatRoomInfo.getName());
map.putString(Constant.APP_KEY, chatRoomInfo.getAppkey());
chatRoomInfo.getOwnerInfo(new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
map.putMap(Constant.OWNER, toJSObject(userInfo));
} else {
WritableMap result = Arguments.createMap();
result.putInt(Constant.CODE, status);
result.putString(Constant.DESCRIPTION, desc);
fail.invoke(result);
}
}
});
map.putInt(Constant.MAX_MEMBER_COUNT, chatRoomInfo.getMaxMemberCount());
map.putString(Constant.DESCRIPTION, chatRoomInfo.getDescription());
map.putInt(Constant.TOTAL_MEMBER_COUNT, chatRoomInfo.getTotalMemberCount());
map.putInt(Constant.CREATE_TIME, chatRoomInfo.getCreateTime());
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static WritableArray toJSArray(List list) {
WritableArray array = Arguments.createArray();
if (list != null) {
for (Object object : list) {
if (object instanceof UserInfo) {
array.pushMap(toJSObject((UserInfo) object));
} else if (object instanceof GroupInfo) {
array.pushMap(toJSObject((GroupInfo) object));
} else if (object instanceof Message) {
array.pushMap(toJSObject((Message) object));
} else if (object instanceof Conversation) {
array.pushMap(toJSObject((Conversation) object));
} else {
array.pushString(object.toString());
}
}
}
return array;
}
public static WritableArray toJSArray(List<ChatRoomInfo> list, Callback fail) {
WritableArray array = Arguments.createArray();
if (null != list) {
for (ChatRoomInfo chatRoomInfo : list) {
array.pushMap(toJSObject(chatRoomInfo, fail));
}
}
return array;
}
public static JSONObject toJSObject(String eventName, JSONObject value) {
JSONObject result = new JSONObject();
try {
result.put("eventName", eventName);
result.put("value", value);
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
|
package base;
import housing.roles.HousingLandlordRole;
import java.util.Map;
import market.roles.MarketCashierRole;
import bank.roles.BankMasterTellerRole;
import base.interfaces.Person;
public class ContactList {
static Map<BankMasterTellerRole, Location> sBankMasterTellers;
static Map<HousingLandlordRole, Location> sHousingLandlords;
static Map<MarketCashierRole, Location> sMarketCashiers;
static Map<Person, Location> sRestaurantHosts; //ALL: Make a host interface and implement a restaurant SHANE: 1 TELL PEOPLE TO ADD A L L
//REX ALL: What else do we need here?
// SHANE: consider above maps with location as a key, instead of value
// so that we can look up the role-person by location
// (finding the location of a role isn't as helpful, methinks)
}
|
package com.marverenic.music;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.SparseIntArray;
import android.view.View;
import com.crashlytics.android.Crashlytics;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.marverenic.music.instances.Album;
import com.marverenic.music.instances.Artist;
import com.marverenic.music.instances.AutoPlaylist;
import com.marverenic.music.instances.Genre;
import com.marverenic.music.instances.Playlist;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.Themes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
public class Library {
public static final String PLAY_COUNT_FILENAME = ".playcount";
public static final String PLAY_COUNT_FILE_COMMENT = "This file contains play count information for Jockey and should not be edited";
public static final int PERMISSION_REQUEST_ID = 0x01;
private static final String AUTO_PLAYLIST_EXTENSION = ".jpl";
private static final ArrayList<Playlist> playlistLib = new ArrayList<>();
private static final ArrayList<Song> songLib = new ArrayList<>();
private static final ArrayList<Artist> artistLib = new ArrayList<>();
private static final ArrayList<Album> albumLib = new ArrayList<>();
private static final ArrayList<Genre> genreLib = new ArrayList<>();
private static final SparseIntArray playCounts = new SparseIntArray();
private static final SparseIntArray skipCounts = new SparseIntArray();
private static final String[] songProjection = new String[]{
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.YEAR,
MediaStore.Audio.Media.DATE_ADDED,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.TRACK
};
private static final String[] artistProjection = new String[]{
MediaStore.Audio.Artists._ID,
MediaStore.Audio.Artists.ARTIST,
};
private static final String[] albumProjection = new String[]{
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.LAST_YEAR,
MediaStore.Audio.Albums.ALBUM_ART
};
private static final String[] playlistProjection = new String[]{
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME
};
private static final String[] genreProjection = new String[]{
MediaStore.Audio.Genres._ID,
MediaStore.Audio.Genres.NAME
};
private static final String[] playlistEntryProjection = new String[]{
MediaStore.Audio.Playlists.Members.TITLE,
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Playlists.Members.ARTIST,
MediaStore.Audio.Playlists.Members.ALBUM,
MediaStore.Audio.Playlists.Members.DURATION,
MediaStore.Audio.Playlists.Members.DATA,
MediaStore.Audio.Playlists.Members.YEAR,
MediaStore.Audio.Playlists.Members.DATE_ADDED,
MediaStore.Audio.Playlists.Members.ALBUM_ID,
MediaStore.Audio.Playlists.Members.ARTIST_ID
};
// LIBRARY LISTENERS
// Since it's important to know when the Library has entries added or removed so we can update
// the UI accordingly, associate listeners to receive callbacks for such events. These listeners
// will get called only when entries are added or removed -- not changed. This lets us do a lot
// of things on the UI like adding and removing playlists without having to create the associated
// Snackbars, AlertDialogs, etc. and is slightly cleaner than passing a callback as a parameter
// to methods that cause such changes since we don't have to instantiate a single-use Object.
private static final ArrayList<PlaylistChangeListener> PLAYLIST_LISTENERS = new ArrayList<>();
public interface PlaylistChangeListener {
void onPlaylistRemoved(Playlist removed);
void onPlaylistAdded(Playlist added);
}
/**
* In certain cases like in {@link com.marverenic.music.fragments.PlaylistFragment}, editing the
* library can break a lot of things if not done carefully. (i.e. if
* {@link android.support.v7.widget.RecyclerView.Adapter#notifyDataSetChanged()} (or similar)
* isn't called after adding a playlist, then the UI process can throw an exception and crash)
*
* If this is the case, call this method to set a callback whenever the library gets updated
* (Not all library update calls will be relevant to the context, but better safe than sorry).
*
* <b>When using this method MAKE SURE TO CALL {@link Library#removePlaylistListener(PlaylistChangeListener)}
* WHEN THE ACTIVITY PAUSES -- OTHERWISE YOU WILL CAUSE A LEAK.</b>
*
* @param listener A {@link PlaylistChangeListener} to act as a callback
* when the library is changed in any way
*/
public static void addPlaylistListener(PlaylistChangeListener listener){
if (!PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.add(listener);
}
/**
* Remove a {@link PlaylistChangeListener} previously added to listen
* for library updates.
* @param listener A {@link PlaylistChangeListener} currently registered
* to recieve a callback when the library gets modified. If it's not already
* registered, then nothing will happen.
*/
public static void removePlaylistListener(PlaylistChangeListener listener){
if (PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.remove(listener);
}
/**
* Private method for notifying registered {@link PlaylistChangeListener}s
* that the library has lost an entry. (Changing entries doesn't matter)
*/
private static void notifyPlaylistRemoved(Playlist removed){
for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistRemoved(removed);
}
/**
* Private method for notifying registered {@link PlaylistChangeListener}s
* that the library has gained an entry. (Changing entries doesn't matter)
*/
private static void notifyPlaylistAdded(Playlist added){
for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistAdded(added);
}
@TargetApi(23)
public static boolean hasRWPermission(Context context){
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED
&& context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
@TargetApi(23)
public static void requestRWPermission(Activity activity){
activity.requestPermissions(
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
PERMISSION_REQUEST_ID);
}
// LIBRARY BUILDING METHODS
public static void scanAll (final Activity activity){
if (hasRWPermission(activity)) {
resetAll();
setPlaylistLib(scanPlaylists(activity));
setSongLib(scanSongs(activity));
setArtistLib(scanArtists(activity));
setAlbumLib(scanAlbums(activity));
setGenreLib(scanGenres(activity));
sort();
}
else{
requestRWPermission(activity);
}
}
/**
* Scans the MediaStore for songs
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Song}s in the MediaStore
*/
public static ArrayList<Song> scanSongs (Context context){
ArrayList<Song> songs = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
songProjection,
MediaStore.Audio.Media.IS_MUSIC + "!= 0",
null,
MediaStore.Audio.Media.TITLE + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Song s = new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? context.getString(R.string.no_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)));
s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK));
songs.add(s);
}
cur.close();
return songs;
}
/**
* Scans the MediaStore for artists
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Artist}s in the MediaStore
*/
public static ArrayList<Artist> scanArtists (Context context){
ArrayList<Artist> artists = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
artistProjection,
null,
null,
MediaStore.Audio.Artists.ARTIST + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
if (!cur.getString(cur.getColumnIndex(MediaStore.Audio.Artists.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) {
artists.add(new Artist(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Artists._ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Artists.ARTIST))));
}
else{
artists.add(new Artist(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Artists._ID)),
context.getString(R.string.no_artist)));
}
}
cur.close();
return artists;
}
/**
* Scans the MediaStore for albums
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Album}s in the MediaStore
*/
public static ArrayList<Album> scanAlbums (Context context){
ArrayList<Album> albums = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
albumProjection,
null,
null,
MediaStore.Audio.Albums.ALBUM + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
albums.add(new Album(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Albums._ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? context.getString(R.string.no_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.LAST_YEAR)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART))));
}
cur.close();
return albums;
}
/**
* Scans the MediaStore for playlists
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Playlist}s in the MediaStore
*/
public static ArrayList<Playlist> scanPlaylists (Context context){
ArrayList<Playlist> playlists = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
playlistProjection,
null,
null,
MediaStore.Audio.Playlists.NAME + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
playlists.add(new Playlist(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists._ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.NAME))));
}
cur.close();
for (Playlist p : scanAutoPlaylists(context)) {
playlists.remove(p);
playlists.add(p);
}
return playlists;
}
/**
* Scans storage for Auto Playlist configurations
* @param context {@link Context} to use to read files on the device
* @return An {@link ArrayList} with the loaded {@link AutoPlaylist}s
*/
public static ArrayList<AutoPlaylist> scanAutoPlaylists (Context context) {
ArrayList<AutoPlaylist> autoPlaylists = new ArrayList<>();
final Gson gson = new Gson();
try {
File externalFiles = new File(context.getExternalFilesDir(null) + "/");
String[] files = externalFiles.list();
for (String s : files) {
if (s.endsWith(AUTO_PLAYLIST_EXTENSION)) {
autoPlaylists.add(gson.fromJson(new FileReader(externalFiles + "/" + s), AutoPlaylist.class));
}
}
} catch (IOException e) {
Crashlytics.logException(e);
}
return autoPlaylists;
}
/**
* Scans the MediaStore for genres
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Genre}s in the MediaStore
*/
public static ArrayList<Genre> scanGenres (Context context){
ArrayList<Genre> genres = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
genreProjection,
null,
null,
MediaStore.Audio.Genres.NAME + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
int thisGenreId = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Genres._ID));
if (cur.getString(cur.getColumnIndex(MediaStore.Audio.Genres.NAME)).equalsIgnoreCase("Unknown")){
genres.add(new Genre(-1, context.getString(R.string.unknown)));
}
else {
genres.add(new Genre(
thisGenreId,
cur.getString(cur.getColumnIndex(MediaStore.Audio.Genres.NAME))));
// Associate all songs in this genre by setting the genreID field of each song in the genre
Cursor genreCur = context.getContentResolver().query(
MediaStore.Audio.Genres.Members.getContentUri("external", thisGenreId),
new String[]{MediaStore.Audio.Media._ID},
MediaStore.Audio.Media.IS_MUSIC + " != 0 ", null, null);
genreCur.moveToFirst();
final int ID_INDEX = genreCur.getColumnIndex(MediaStore.Audio.Media._ID);
for (int j = 0; j < genreCur.getCount(); j++) {
genreCur.moveToPosition(j);
final Song s = findSongById(genreCur.getInt(ID_INDEX));
if (s != null) s.genreId = thisGenreId;
}
genreCur.close();
}
}
cur.close();
return genres;
}
// LIBRARY STORAGE METHODS
/**
* Remove all library entries from memory
*/
public static void resetAll(){
playlistLib.clear();
songLib.clear();
artistLib.clear();
albumLib.clear();
genreLib.clear();
}
/**
* Replace the playlist library in memory with another one
* @param newLib The new playlist library
*/
public static void setPlaylistLib(ArrayList<Playlist> newLib){
playlistLib.clear();
playlistLib.addAll(newLib);
}
/**
* Replace the song library in memory with another one
* @param newLib The new song library
*/
public static void setSongLib(ArrayList<Song> newLib){
songLib.clear();
songLib.addAll(newLib);
}
/**
* Replace the album library in memory with another one
* @param newLib The new album library
*/
public static void setAlbumLib(ArrayList<Album> newLib){
albumLib.clear();
albumLib.addAll(newLib);
}
/**
* Replace the artist library in memory with another one
* @param newLib The new artist library
*/
public static void setArtistLib(ArrayList<Artist> newLib){
artistLib.clear();
artistLib.addAll(newLib);
}
/**
* Replace the genre library in memory with another one
* @param newLib The new genre library
*/
public static void setGenreLib(ArrayList<Genre> newLib){
genreLib.clear();
genreLib.addAll(newLib);
}
/**
* Sorts the libraries in memory using the default {@link Library} sort methods
*/
public static void sort (){
sortSongList(songLib);
sortAlbumList(albumLib);
sortArtistList(artistLib);
sortPlaylistList(playlistLib);
sortGenreList(genreLib);
}
/**
* @return true if the library is populated with any entries
*/
public static boolean isEmpty (){
return songLib.isEmpty() && albumLib.isEmpty() && artistLib.isEmpty() && playlistLib.isEmpty() && genreLib.isEmpty();
}
/**
* @return An {@link ArrayList} of {@link Playlist}s in the MediaStore
*/
public static ArrayList<Playlist> getPlaylists(){
return playlistLib;
}
/**
* @return An {@link ArrayList} of {@link Song}s in the MediaStore
*/
public static ArrayList<Song> getSongs(){
return songLib;
}
/**
* @return An {@link ArrayList} of {@link Album}s in the MediaStore
*/
public static ArrayList<Album> getAlbums(){
return albumLib;
}
/**
* @return An {@link ArrayList} of {@link Artist}s in the MediaStore
*/
public static ArrayList<Artist> getArtists(){
return artistLib;
}
/**
* @return An {@link ArrayList} of {@link Genre}s in the MediaStore
*/
public static ArrayList<Genre> getGenres(){
return genreLib;
}
// LIBRARY SORT METHODS
/**
* Sorts an {@link ArrayList} of {@link Song}s by name, ignoring leading "the "'s and "a "'s
* @param songs the {@link ArrayList} to be sorted
*/
public static void sortSongList(final ArrayList<Song> songs){
Comparator<Song> songComparator = new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
String o1c = o1.songName.toLowerCase(Locale.ENGLISH);
String o2c = o2.songName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
return o1c.compareTo(o2c);
}
};
Collections.sort(songs, songComparator);
}
/**
* Sorts an {@link ArrayList} of {@link Album}s by name, ignoring leading "the "'s and "a "'s
* @param albums the {@link ArrayList} to be sorted
*/
public static void sortAlbumList (final ArrayList<Album> albums){
Comparator<Album> albumComparator = new Comparator<Album>() {
@Override
public int compare(Album o1, Album o2) {
String o1c = o1.albumName.toLowerCase(Locale.ENGLISH);
String o2c = o2.albumName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
return o1c.compareTo(o2c);
}
};
Collections.sort(albums, albumComparator);
}
/**
* Sorts an {@link ArrayList} of {@link Artist}s by name, ignoring leading "the "'s and "a "'s
* @param artists the {@link ArrayList} to be sorted
*/
public static void sortArtistList (final ArrayList<Artist> artists){
Comparator<Artist> artistComparator = new Comparator<Artist>() {
@Override
public int compare(Artist o1, Artist o2) {
String o1c = o1.artistName.toLowerCase(Locale.ENGLISH);
String o2c = o2.artistName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
return o1c.compareTo(o2c);
}
};
Collections.sort(artists, artistComparator);
}
/**
* Sorts an {@link ArrayList} of {@link Playlist}s by name
* @param playlists {@link ArrayList} to be sorted
*/
public static void sortPlaylistList (final ArrayList<Playlist> playlists){
Comparator<Playlist> playlistComparator = new Comparator<Playlist>() {
@Override
public int compare(Playlist o1, Playlist o2) {
if (!o1.getClass().equals(o2.getClass())) {
if (o1 instanceof AutoPlaylist) {
return -1;
}
if (o2 instanceof AutoPlaylist) {
return 1;
}
}
return o1.playlistName.compareToIgnoreCase(o2.playlistName);
}
};
Collections.sort(playlists, playlistComparator);
}
/**
* Sorts an {@link ArrayList} of {@link Genre}s by name
* @param genres the {@link ArrayList} to be sorted
*/
public static void sortGenreList (final ArrayList<Genre> genres){
Comparator<Genre> genreComparator = new Comparator<Genre>() {
@Override
public int compare(Genre o1, Genre o2) {
return o1.genreName.compareToIgnoreCase(o2.genreName);
}
};
Collections.sort(genres, genreComparator);
}
// LIBRARY SEARCH METHODS
/**
* Finds a {@link Song} in the library based on its Id
* @param songId the MediaStore Id of the {@link Song}
* @return A {@link Song} with a matching Id
*/
public static Song findSongById (int songId){
for (Song s : songLib){
if (s.songId == songId){
return s;
}
}
return null;
}
/**
* Build an {@link ArrayList} of {@link Song}s from a list of id's. Doesn't require the library to be loaded
* @param songIDs The list of song ids to convert to {@link Song}s
* @param context The {@link Context} used to open a {@link Cursor}
* @return An {@link ArrayList} of {@link Song}s with ids matching those of the songIDs parameter
*/
public static ArrayList<Song> buildSongListFromIds (int[] songIDs, Context context){
ArrayList<Song> contents = new ArrayList<>();
if (songIDs.length == 0) return contents;
String query = MediaStore.Audio.Media._ID + " IN(?";
String[] ids = new String[songIDs.length];
ids[0] = Integer.toString(songIDs[0]);
for (int i = 1; i < songIDs.length; i++){
query += ",?";
ids[i] = Integer.toString(songIDs[i]);
}
query += ")";
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
songProjection,
query,
ids,
MediaStore.Audio.Media.TITLE + " ASC");
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Song s = new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? context.getString(R.string.no_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)));
s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK));
contents.add(s);
}
cur.close();
// Sort the contents of the list so that it matches the order of the int array
ArrayList<Song> songs = new ArrayList<>();
Song dummy = new Song(null, 0, null, null, 0, null, 0, 0, 0, 0);
for (int i : songIDs){
dummy.songId = i;
// Because Songs are equal if their ids are equal, we can use a dummy song with the ID
// we want to find it in the list
songs.add(contents.get(contents.indexOf(dummy)));
}
return songs;
}
/**
* Finds a {@link Artist} in the library based on its Id
* @param artistId the MediaStore Id of the {@link Artist}
* @return A {@link Artist} with a matching Id
*/
public static Artist findArtistById (int artistId){
for (Artist a : artistLib){
if (a.artistId == artistId){
return a;
}
}
return null;
}
/**
* Finds a {@link Album} in a library based on its Id
* @param albumId the MediaStore Id of the {@link Album}
* @return A {@link Album} with a matching Id
*/
public static Album findAlbumById (int albumId){
// Returns the first Artist object in the library with a matching id
for (Album a : albumLib){
if (a.albumId == albumId){
return a;
}
}
return null;
}
/**
* Finds a {@link Genre} in a library based on its Id
* @param genreId the MediaStore Id of the {@link Genre}
* @return A {@link Genre} with a matching Id
*/
public static Genre findGenreById (int genreId){
// Returns the first Genre object in the library with a matching id
for (Genre g : genreLib){
if (g.genreId == genreId){
return g;
}
}
return null;
}
public static Artist findArtistByName (String artistName){
final String trimmedQuery = artistName.trim();
for (Artist a : artistLib){
if (a.artistName.equalsIgnoreCase(trimmedQuery))
return a;
}
return null;
}
// CONTENTS QUERY METHODS
/**
* Get a list of songs in a certain playlist
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the playlist
*/
public static ArrayList<Song> getPlaylistEntries (Context context, Playlist playlist){
if (playlist instanceof AutoPlaylist){
return ((AutoPlaylist) playlist).generatePlaylist(context);
}
ArrayList<Song> songEntries = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
playlistEntryProjection,
MediaStore.Audio.Media.IS_MUSIC + " != 0", null, null);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
songEntries.add(new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST_ID))));
}
cur.close();
return songEntries;
}
/**
* Get a list of songs on a certain album
* @param album The {@link Album} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the album
*/
public static ArrayList<Song> getAlbumEntries (Album album){
ArrayList<Song> songEntries = new ArrayList<>();
for (Song s : songLib){
if (s.albumId == album.albumId){
songEntries.add(s);
}
}
Collections.sort(songEntries, new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
return ((Integer) o1.trackNumber).compareTo(o2.trackNumber);
}
});
return songEntries;
}
/**
* Get a list of songs by a certain artist
* @param artist The {@link Artist} to get the entries of
* @return An {@link ArrayList} of {@link Song}s by the artist
*/
public static ArrayList<Song> getArtistSongEntries (Artist artist){
ArrayList<Song> songEntries = new ArrayList<>();
for(Song s : songLib){
if (s.artistId == artist.artistId){
songEntries.add(s);
}
}
return songEntries;
}
/**
* Get a list of albums by a certain artist
* @param artist The {@link Artist} to get the entries of
* @return An {@link ArrayList} of {@link Album}s by the artist
*/
public static ArrayList<Album> getArtistAlbumEntries (Artist artist){
ArrayList<Album> albumEntries = new ArrayList<>();
for (Album a : albumLib){
if (a.artistId == artist.artistId){
albumEntries.add(a);
}
}
return albumEntries;
}
/**
* Get a list of songs in a certain genre
* @param genre The {@link Genre} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the genre
*/
public static ArrayList<Song> getGenreEntries (Genre genre){
ArrayList<Song> songEntries = new ArrayList<>();
for(Song s : songLib){
if (s.genreId == genre.genreId){
songEntries.add(s);
}
}
return songEntries;
}
// PLAY COUNT READING & ACCESSING METHODS
public static void loadPlayCounts(Context context) {
playCounts.clear();
skipCounts.clear();
try {
Properties countProperties = openPlayCountFile(context);
Enumeration iterator = countProperties.propertyNames();
while (iterator.hasMoreElements()){
String key = (String) iterator.nextElement();
String value = countProperties.getProperty(key, "0,0");
final String[] originalValues = value.split(",");
int playCount = Integer.parseInt(originalValues[0]);
int skipCount = Integer.parseInt(originalValues[1]);
playCounts.put(Integer.parseInt(key), playCount);
skipCounts.put(Integer.parseInt(key), skipCount);
}
}
catch (IOException e){
Crashlytics.logException(e);
}
}
/**
* Returns a readable {@link Properties} to be used with {@link Library#loadPlayCounts(Context)}
* @param context Used to read files from external storage
* @return A {@link Properties} object that has been initialized with values saved by
* {@link Player#logPlayCount(long, boolean)} and {@link Player#savePlayCountFile()}
* @throws IOException
*/
private static Properties openPlayCountFile(Context context) throws IOException{
File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME);
if (!file.exists()) //noinspection ResultOfMethodCallIgnored
file.createNewFile();
InputStream is = new FileInputStream(file);
Properties playCountHashtable;
try {
playCountHashtable = new Properties();
playCountHashtable.load(is);
}
finally {
is.close();
}
return playCountHashtable;
}
/**
* Returns the number of skips a song has. Note that you may need to call
* {@link Library#loadPlayCounts(Context)} in case the data has gone stale
* @param songId The {@link Song#songId} as written in the MediaStore
* @return The number of times a song has been skipped
*/
public static int getSkipCount (int songId){
return skipCounts.get(songId, 0);
}
/**
* Returns the number of plays a song has. Note that you may need to call
* {@link Library#loadPlayCounts(Context)} in case the data has gone stale
* @param songId The {@link Song#songId} as written in the MediaStore
* @return The number of times a song has been plays
*/
public static int getPlayCount (int songId){
return playCounts.get(songId, 0);
}
// PLAYLIST WRITING METHODS
/**
* Add a new playlist to the MediaStore
* @param view A {@link View} to put a {@link Snackbar} in. Will also be used to get a {@link Context}.
* @param playlistName The name of the new playlist
* @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist
* @return The Playlist that was added to the library
*/
public static Playlist createPlaylist(final View view, final String playlistName, @Nullable final ArrayList<Song> songList){
final Context context = view.getContext();
String trimmedName = playlistName.trim();
setPlaylistLib(scanPlaylists(context));
String error = verifyPlaylistName(context, trimmedName);
if (error != null){
Snackbar
.make(
view,
error,
Snackbar.LENGTH_SHORT)
.show();
return null;
}
// Add the playlist to the MediaStore
final Playlist created = makePlaylist(context, trimmedName, songList);
Snackbar
.make(
view,
String.format(context.getResources().getString(R.string.message_created_playlist), playlistName),
Snackbar.LENGTH_LONG)
.setAction(
R.string.action_undo,
new View.OnClickListener() {
@Override
public void onClick(View v) {
deletePlaylist(context, created);
}
})
.show();
return created;
}
/**
* Test a playlist name to make sure it is valid when making a new playlist. Invalid playlist names
* are instance_empty or already exist in the MediaStore
* @param context A {@link Context} used to get localized Strings
* @param playlistName The playlist name that needs to be validated
* @return null if there is no error, or a {@link String} describing the error that can be
* presented to the user
*/
public static String verifyPlaylistName (final Context context, final String playlistName){
if (playlistName.length() == 0) return null;
String trimmedName = playlistName.trim();
if (trimmedName.length() == 0){
return context.getResources().getString(R.string.error_hint_empty_playlist);
}
for (Playlist p : playlistLib){
if (p.playlistName.equalsIgnoreCase(trimmedName)){
return context.getResources().getString(R.string.error_hint_duplicate_playlist);
}
}
return null;
}
/**
* Removes a playlist from the MediaStore
* @param view A {@link View} to show a {@link Snackbar} and to get a {@link Context} used to edit the MediaStore
* @param playlist A {@link Playlist} which will be removed from the MediaStore
*/
public static void removePlaylist(final View view, final Playlist playlist){
final Context context = view.getContext();
final ArrayList<Song> entries = getPlaylistEntries(context, playlist);
deletePlaylist(context, playlist);
Snackbar
.make(
view,
String.format(context.getString(R.string.message_removed_playlist), playlist),
Snackbar.LENGTH_LONG)
.setAction(
context.getString(R.string.action_undo),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (playlist instanceof AutoPlaylist) {
makeAutoPlaylist(context, (AutoPlaylist) playlist);
} else {
makePlaylist(context, playlist.playlistName, entries);
}
}
})
.show();
}
/**
* Replace the entries of a playlist in the MediaStore with a new {@link ArrayList} of {@link Song}s
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param newSongList An {@link ArrayList} of {@link Song}s to overwrite the list contained in the MediaStore
*/
public static void editPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> newSongList){
// Clear the playlist...
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.delete(uri, null, null);
// Then add all of the songs to it
ContentValues[] values = new ContentValues[newSongList.size()];
for (int i = 0; i < newSongList.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, newSongList.get(i).songId);
}
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
/**
* Append a song to the end of a playlist. Alerts the user about duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param song The {@link Song} to be added to the playlist in the MediaStore
*/
public static void addPlaylistEntry(final Context context, final Playlist playlist, final Song song){
// Public method to add a song to a playlist
// Checks the playlist for duplicate entries
if (getPlaylistEntries(context, playlist).contains(song)){
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, 1))
.setMessage(context.getString(R.string.playlist_confirm_duplicate, playlist, song))
.setPositiveButton(R.string.action_add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongToEndOfPlaylist(context, playlist, song);
}
})
.setNegativeButton(R.string.action_cancel, null)
.show();
Themes.themeAlertDialog(dialog);
}
else{
addSongToEndOfPlaylist(context, playlist, song);
}
}
/**
* Append a list of songs to the end of a playlist. Alerts the user about duplicates
* @param view A {@link View} to put a {@link android.support.design.widget.Snackbar} in. Will
* also be used to get a {@link Context}.
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore
*/
public static void addPlaylistEntries(final View view, final Playlist playlist, final ArrayList<Song> songs){
// Public method to add songs to a playlist
// Checks the playlist for duplicate entries
final Context context = view.getContext();
int duplicateCount = 0;
final ArrayList<Song> currentEntries = getPlaylistEntries(context, playlist);
final ArrayList<Song> newEntries = new ArrayList<>();
for (Song s : songs){
if (currentEntries.contains(s))duplicateCount++;
else newEntries.add(s);
}
if (duplicateCount > 0){
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, duplicateCount));
if (duplicateCount == songs.size()) {
alert
.setMessage(context.getString(R.string.playlist_confirm_all_duplicates, duplicateCount))
.setPositiveButton(context.getResources().getQuantityText(R.plurals.playlist_positive_add_duplicates, duplicateCount), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(context.getString(R.string.action_undo), new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNeutralButton(context.getString(R.string.action_cancel), null);
}
else{
alert
.setMessage(context.getResources().getQuantityString(R.plurals.playlist_confirm_some_duplicates, duplicateCount, duplicateCount))
.setPositiveButton(R.string.action_add_new, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, newEntries);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNegativeButton(R.string.action_add_all, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNeutralButton(R.string.action_cancel, null);
}
Themes.themeAlertDialog(alert.show());
}
else{
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
}
// MEDIA_STORE EDIT METHODS
// These methods only perform actions to the MediaStore. They do not validate inputs, and they
// do not display confirmation messages to the user.
/**
* Add a new playlist to the MediaStore. Outside of this class, use
* {@link Library#createPlaylist(View, String, ArrayList)} instead
* <b>This method DOES NOT validate inputs or display a confirmation message to the user</b>.
* @param context A {@link Context} used to edit the MediaStore
* @param playlistName The name of the new playlist
* @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist
* @return The Playlist that was added to the library
*/
private static Playlist makePlaylist(final Context context, final String playlistName, @Nullable final ArrayList<Song> songList){
String trimmedName = playlistName.trim();
// Add the playlist to the MediaStore
ContentValues mInserts = new ContentValues();
mInserts.put(MediaStore.Audio.Playlists.NAME, trimmedName);
mInserts.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis());
mInserts.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis());
Uri newPlaylistUri = context.getContentResolver().insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mInserts);
// Update the playlist library & resort it
setPlaylistLib(scanPlaylists(context));
sortPlaylistList(playlistLib);
// Get the id of the new playlist
Cursor cursor = context.getContentResolver().query(
newPlaylistUri,
new String[] {MediaStore.Audio.Playlists._ID},
null, null, null);
cursor.moveToFirst();
final Playlist playlist = new Playlist(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)), playlistName);
cursor.close();
// If we have a list of songs, associate it with the playlist
if(songList != null) {
ContentValues[] values = new ContentValues[songList.size()];
for (int i = 0; i < songList.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songList.get(i).songId);
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
notifyPlaylistAdded(playlist);
return playlist;
}
/**
* Removes a playlist from the MediaStore
* @param context A {@link Context} to update the MediaStore
* @param playlist A {@link Playlist} whose matching playlist will be removed from the MediaStore
*/
public static void deletePlaylist(final Context context, final Playlist playlist){
// Remove the playlist from the MediaStore
context.getContentResolver().delete(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
MediaStore.Audio.Playlists._ID + "=?",
new String[]{playlist.playlistId + ""});
// If the playlist is an AutoPlaylist, make sure to delete its configuration
if (playlist instanceof AutoPlaylist) {
//noinspection ResultOfMethodCallIgnored
new File(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION).delete();
}
// Update the playlist library & resort it
playlistLib.clear();
setPlaylistLib(scanPlaylists(context));
sortPlaylistList(playlistLib);
notifyPlaylistRemoved(playlist);
}
/**
* Append a song to the end of a playlist. Doesn't check for duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param song The {@link Song} to be added to the playlist in the MediaStore
*/
private static void addSongToEndOfPlaylist (final Context context, final Playlist playlist, final Song song){
// Private method to add a song to a playlist
// This method does the actual operation to the MediaStore
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
null, null, null,
MediaStore.Audio.Playlists.Members.TRACK + " ASC");
long count = 0;
if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK));
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1);
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, song.songId);
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.insert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
/**
* Append a list of songs to the end of a playlist. Doesn't check for duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore
*/
private static void addSongsToEndOfPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> songs){
// Private method to add a song to a playlist
// This method does the actual operation to the MediaStore
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
null, null, null,
MediaStore.Audio.Playlists.Members.TRACK + " ASC");
long count = 0;
if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK));
cur.close();
ContentValues[] values = new ContentValues[songs.size()];
for (int i = 0; i < songs.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(i).songId);
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
// AUTO PLAYLIST EDIT METHODS
/**
* Add an {@link AutoPlaylist} to the library.
* @param playlist the AutoPlaylist to be added to the library. The configuration of this
* playlist will be saved so that it can be loaded when the library is next
* rescanned, and a "stale" copy with current entries will be written in the
* MediaStore so that other applications may access this playlist
*/
public static void makeAutoPlaylist(Context context, AutoPlaylist playlist) {
try {
// Add the playlist to the MediaStore
Playlist p = makePlaylist(context, playlist.playlistName, playlist.generatePlaylist(context));
// By default, makePlaylist adds it to the library array. We don't want that
playlistLib.remove(p);
// Assign the auto playlist's ID to match the one in the MediaStore
playlist.playlistId = p.playlistId;
// Save the playlist configuration with GSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION);
playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class));
playlistWriter.close();
// Add the playlist to the library and resort the playlist library
playlistLib.add(playlist);
sortPlaylistList(playlistLib);
notifyPlaylistAdded(playlist);
} catch (IOException e) {
Crashlytics.logException(e);
}
}
public static void editAutoPlaylist(Context context, AutoPlaylist playlist) {
try {
// Save the playlist configuration with GSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION);
playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class));
playlistWriter.close();
// Edit the contents of this playlist in the MediaStore
editPlaylist(context, playlist, playlist.generatePlaylist(context));
// Remove the old index of this playlist. Since playlists are compared by Id's, this
// will remove the old index
playlistLib.remove(playlist);
// Add the playlist again. This makes sure that if the values have been cloned before
// being changed that their values will be updated without having to rescan the
// entire library
playlistLib.add(playlist);
sortPlaylistList(playlistLib);
} catch (IOException e) {
Crashlytics.logException(e);
}
}
// Media file open method
/**
* Get a list of songs to play for a certain input file. If a song is passed as the file, then
* the list will include other songs in the same directory. If a playlist is passed as the file,
* then the playlist will be opened as a regular playlist.
*
* @param activity An {@link Activity} to use when building the list
* @param file The {@link File} which the list will be built around
* @param type The MIME type of the file being opened
* @param queue An {@link ArrayList} which will be populated with the {@link Song}s
* @return The position that this list should be started from
* @throws IOException
*/
public static int getSongListFromFile(Activity activity, File file, String type, final ArrayList<Song> queue) throws IOException{
// A somewhat convoluted method for getting a list of songs from a path
// Songs are put into the queue array list
// The integer returned is the position in this queue that corresponds to the requested song
if (isEmpty()){
// We depend on the library being scanned, so make sure it's scanned before we go any further
scanAll(activity);
}
// PLAYLISTS
if (type.equals("audio/x-mpegurl") || type.equals("audio/x-scpls") || type.equals("application/vnd.ms-wpl")){
// If a playlist was opened, try to find and play its entry from the MediaStore
Cursor cur = activity.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Playlists.DATA + "=?",
new String[] {file.getPath()},
MediaStore.Audio.Playlists.NAME + " ASC");
// If the media store contains this playlist, play it like a regular playlist
if (cur.getCount() > 0){
cur.moveToFirst();
queue.addAll(getPlaylistEntries(activity, new Playlist(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists._ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.NAME)))));
}
//TODO Attempt to manually read common playlist writing schemes
/*else{
// If the MediaStore doesn't contain this playlist, attempt to read it manually
Scanner sc = new Scanner(file);
ArrayList<String> lines = new ArrayList<>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
if (lines.size() > 0){
// Do stuff
}
}*/
cur.close();
// Return 0 to start at the beginning of the playlist
return 0;
}
// ALL OTHER TYPES OF MEDIA
else {
// If the file isn't a playlist, use a content resolver to find the song and play it
// Find all songs in the directory
Cursor cur = activity.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.DATA + " like ?",
new String[] {"%" + file.getParent() + "/%"},
MediaStore.Audio.Media.DATA + " ASC");
// Create song objects to match those in the music library
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
queue.add(new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? activity.getString(R.string.unknown_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID))));
}
cur.close();
// Find the position of the song that should be played
for(int i = 0; i < queue.size(); i++){
if (queue.get(i).location.equals(file.getPath())) return i;
}
}
return 0;
}
}
|
package com.ternaryop.utils;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Pair;
public class UriUtils {
public static final String SCHEMA_FILE = "file";
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri)
{
//check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String[] projection = {
MediaStore.Images.Media.DATA
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
public static Pair<String, String> getRealPathAndMimeFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.MIME_TYPE };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor == null) {
return null;
}
cursor.moveToFirst();
return Pair.create(getPath(context, contentUri),
cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE)));
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static URI encodeIllegalChar(final String uriStr, String enc, int retryCount) throws URISyntaxException, UnsupportedEncodingException {
String _uriStr = uriStr;
while (true) {
try {
return new URI(_uriStr);
} catch(URISyntaxException e) {
String reason = e.getReason();
if (reason == null ||
!(
reason.contains("in path") ||
reason.contains("in query") ||
reason.contains("in fragment")
)
) {
throw e;
}
if (0 > retryCount
throw e;
}
String input = e.getInput();
int idx = e.getIndex();
String illChar = String.valueOf(input.charAt(idx));
_uriStr = input.replace(illChar, URLEncoder.encode(illChar, enc));
}
}
}
}
|
package com.twosheds.pi;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
static final double ACCURACY = 0.00000000000001;
private static final int EVENT_NEW_VALUE = 1;
private static final int EVENT_FINISHED_CALCULATION = 2;
private Random random;
private static int countInside;
private static int countTotal;
private static boolean isRunning;
private GraphView graphView;
private TextView piView;
private ImageView transparentPiView;
private TextView stepView;
private Button startButton;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
int event = message.what;
switch (event) {
case EVENT_NEW_VALUE:
updateViews((double) message.obj);
break;
case EVENT_FINISHED_CALCULATION:
stopCalculation();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
graphView = (GraphView) findViewById(R.id.graph);
piView = (TextView) findViewById(R.id.pi);
transparentPiView = (ImageView) findViewById(R.id.pi_transparent);
stepView = (TextView) findViewById(R.id.steps);
startButton = (Button) findViewById(R.id.button_start);
countTotal = 0;
countInside = 0;
random = new Random();
updateViews(0.0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onStartCalculation(View view) {
if (isRunning) {
stopCalculation();
} else {
isRunning = true;
startButton.setText(R.string.action_stop);
Thread drawThread = new Thread() {
@Override
public void run() {
double oldPi = 10.0;
double pi = 20.0;
graphView.clearPoints();
while (isRunning && Math.abs(oldPi - pi) > ACCURACY) {
double x = random.nextDouble() * 2.0d - 1.0d;
double y = random.nextDouble() * 2.0d - 1.0d;
boolean isInside = (x * x + y * y) < 1.0d;
if (isInside) {
countInside++;
}
countTotal++;
if (countTotal != countInside && countInside > 0) {
oldPi = pi;
}
pi = (double) countInside * 4.0d / (double) countTotal;
Message msg = handler.obtainMessage(EVENT_NEW_VALUE);
msg.obj = pi;
msg.sendToTarget();
graphView.drawPoint(x, y, isInside);
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.obtainMessage(EVENT_FINISHED_CALCULATION).sendToTarget();
}
};
drawThread.start();
}
}
private void updateViews(double pi) {
piView.setText(getString(R.string.pi, pi));
stepView.setText(getString(R.string.iteration, countTotal));
transparentPiView.setAlpha(getAlpha(pi));
}
private void stopCalculation() {
isRunning = false;
startButton.setText(R.string.action_start);
countTotal = 0;
countInside = 0;
}
private float getAlpha(double pi) {
double accuracy = Math.min(1.0, Math.abs(Math.PI - pi));
double accuracyFactor = Math.log10(MainActivity.ACCURACY / accuracy) / Math.log10(MainActivity.ACCURACY);
return 1 - Math.min(1, (float) (1 * accuracyFactor));
}
}
|
package com.zsx.util;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
import com.zsx.debug.LogUtil;
import java.io.File;
public class Lib_Util_Intent {
/**
*
*
* @param mContext
* @param smstext
* @return
*/
public static void sendSms(Context mContext, String smstext) {
Uri smsToUri = Uri.parse("smsto:");
Intent mIntent = new Intent(Intent.ACTION_SENDTO,
smsToUri);
mIntent.putExtra("sms_body", smstext);
mContext.startActivity(mIntent);
}
/**
*
*
* @param mContext Context
* @param toUser
* @param title
* @param text
* @return
*/
public static void sendMail(Context mContext, String[] toUser,
String title, String text) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// emailIntent.setType("text/plain"); //
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL, toUser);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, title);
emailIntent.putExtra(Intent.EXTRA_TEXT, text);
mContext.startActivity(Intent.createChooser(emailIntent,
"Choose Email Client"));
}
/**
* App
*
* @param context
* @param packageName
* @throws ActivityNotFoundException
* @throws SecurityException
*/
public static void uninstallApp(Context context, String packageName)
throws ActivityNotFoundException, SecurityException {
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
Uri.parse("package:" + packageName));
context.startActivity(uninstallIntent);
}
/**
*
*
* @param activityTitle Activity
* @param msgTitle
* @param msgText
* @param imgPath null
*/
public void shareMsg(Context context, String activityTitle,
String msgTitle, String msgText, String imgPath) {
Intent intent = new Intent(Intent.ACTION_SEND);
if (imgPath == null || imgPath.equals("")) {
intent.setType("text/plain");
} else {
File f = new File(imgPath);
if (f != null && f.exists() && f.isFile()) {
intent.setType("image/jpg");
//sms_body
intent.putExtra("sms_body", msgText);
Uri u = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_STREAM, u);
}
}
intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
intent.putExtra(Intent.EXTRA_TEXT, msgText);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(Intent.createChooser(intent, activityTitle));
} catch (ActivityNotFoundException ex) {
Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
}
}
public static void startInstallAPK(Context context, String apkPath) {
File apk = new File(apkPath);
if (!apk.exists()) {
LogUtil.e(Lib_Util_Intent.class, "" + apkPath);
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apk),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
public void a() {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
/** --Task */
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
public static boolean installFromMarket(Context activity) {
try {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + activity.getPackageName())));
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public static Intent startApp(Activity activity, String packageName) {
Intent intent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
return intent;
}
}
|
package beast.core;
import beast.core.parameter.RealParameter;
import beast.core.util.Log;
import java.io.File;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;
/**
* Represents input of a BEASTObject class.
* Inputs connect BEASTObjects with outputs of other BEASTObjects,
* e.g. a Logger can get the result it needs to log from a
* BEASTObject that actually performs a calculation.
*/
public class Input<T> {
/**
* input name, used for identification when getting/setting values of a plug-in *
*/
String name = "";
/**
* short description of the function of this particular input *
*/
String tipText = "";
/**
* value represented by this input
*/
T value;
/**
* Type of T, automatically determined when setting a new value.
* Used for type checking.
*/
protected Class<?> theClass;
/**
* validation rules *
*/
public enum Validate {
OPTIONAL, REQUIRED, XOR, FORBIDDEN
}
// (Q2R) I am surprised the default is not required ....
Validate rule = Validate.OPTIONAL;
/**
* used only if validation rule is XOR *
*/
Input<?> other;
public T defaultValue;
/**
* Possible values for enumerations, e.g. if
* an input can be any of "constant", "linear", "quadratic"
* this array contains these values. Used for validation and user interfaces.
*/
public T[] possibleValues;
/**
* constructors *
*/
public Input() {
}
/**
* simple constructor, requiring only the input name and tiptext
*/
public Input(String sName, String sTipText) {
name = sName;
tipText = sTipText;
value = null;
checkName();
} // c'tor
/**
* simple constructor as above but with type pre-specified.
* This allows inputs of types that cannot be determined through
* introspection, such as template class inputs, e.g. Input<Parameter<?>>
*/
public Input(String sName, String sTipText, Class<?> theClass) {
this(sName, sTipText);
this.theClass = theClass;
} // c'tor
/**
* constructor for List<>
*/
public Input(String sName, String sTipText, T startValue) {
this(sName, sTipText);
value = startValue;
defaultValue = startValue;
} // c'tor
/**
* constructor for List<> with type specified
*/
public Input(String sName, String sTipText, T startValue, Class<?> theClass) {
this(sName, sTipText, startValue);
this.theClass = theClass;
} // c'tor
/**
* constructor for List<> with XOR rules
*/
public Input(String sName, String sTipText, T startValue, Validate rule, Input<?> other) {
this(sName, sTipText, startValue);
if (rule != Validate.XOR) {
System.err.println("Programmer error: input rule should be XOR for this Input constructor");
}
this.rule = rule;
this.other = other;
this.other.other = this;
this.other.rule = rule;
checkName();
} // c'tor
/**
* constructor for List<> with XOR rules with type specified
*/
public Input(String sName, String sTipText, T startValue, Validate rule, Input<?> other, Class<?> theClass) {
this(sName, sTipText, startValue, rule, other);
this.theClass = theClass;
} // c'tor
/**
* Constructor for REQUIRED rules for List-inputs, i.e. lists that require
* at least one value to be specified.
* If optional (i.e. no value need to be specified), leave the rule out
*/
public Input(String sName, String sTipText, T startValue, Validate rule) {
this(sName, sTipText, startValue);
/*if (rule != Validate.REQUIRED) {
System.err.println("Programmer error: input rule should be REQUIRED for this Input constructor"
+ " (" + sName + ")");
}*/
this.rule = rule;
} // c'tor
/**
* constructor for REQUIRED rules for List-inputs, with type pre-specified
*/
public Input(String sName, String sTipText, T startValue, Validate rule, Class<?> type) {
this(sName, sTipText, startValue, rule);
theClass = type;
} // c'tor
/**
* constructor for REQUIRED rules
*/
public Input(String sName, String sTipText, Validate rule) {
this(sName, sTipText);
if (rule != Validate.REQUIRED) {
System.err.println("Programmer error: input rule should be REQUIRED for this Input constructor"
+ " (" + sName + ")");
}
this.rule = rule;
} // c'tor
/**
* constructor for REQUIRED rules, with type pre-specified
*/
public Input(String sName, String sTipText, Validate rule, Class<?> type) {
this(sName, sTipText, rule);
this.theClass = type;
}
/**
* constructor for XOR rules *
*/
public Input(String sName, String sTipText, Validate rule, Input<?> other) {
this(sName, sTipText);
if (rule != Validate.XOR) {
System.err.println("Programmer error: input rule should be XOR for this Input constructor");
}
this.rule = rule;
this.other = other;
this.other.other = this;
this.other.rule = rule;
} // c'tor
/**
* constructor for XOR rules, with type pre-specified
*/
public Input(String sName, String sTipText, Validate rule, Input<?> other, Class<?> type) {
this(sName, sTipText, rule, other);
this.theClass = type;
}
/**
* constructor for enumeration.
* Typical usage is with an array of possible String values, say ["constant","exponential","lognormal"]
* Furthermore, a default value is required (should we have another constructor that could leave
* the value optional? When providing a 'no-input' entry in the list and setting that as the default,
* that should cover that situation.)
*/
public Input(String sName, String sTipText, T startValue, T[] sPossibleValues) {
name = sName;
tipText = sTipText;
value = startValue;
defaultValue = startValue;
possibleValues = sPossibleValues;
checkName();
} // c'tor
/**
* check name is not one of the reserved ones *
*/
private void checkName() {
if (name.toLowerCase().equals("id") ||
name.toLowerCase().equals("idref") ||
name.toLowerCase().equals("spec") ||
name.toLowerCase().equals("name")) {
System.err.println("Found an input with invalid name: " + name);
System.err.println("'id', 'idref', 'spec' and 'name' are reserved and cannot be used");
System.exit(0);
}
}
/**
* various setters and getters
*/
public String getName() {
return name;
}
public String getTipText() {
return tipText;
}
public String getHTMLTipText() {
return "<html>" + tipText.replaceAll("\n", "<br>") + "</html>";
}
public String getValueTipText() {
if (theClass == Boolean.class) {
return ("[true|false]");
}
if (theClass == Integer.class) {
return ("<integer>");
}
if (theClass == Long.class) {
return ("<long>");
}
if (theClass == Double.class) {
return ("<double>");
}
if (theClass == String.class) {
return "<string>";
}
if (theClass == File.class) {
return "<filename>";
}
if (theClass.isEnum()) {
return Arrays.toString(possibleValues).replaceAll(",", "|");
}
return "";
}
public Class<?> getType() {
return theClass;
}
public void setType(Class<?> theClass) {
this.theClass = theClass;
}
public Validate getRule() {
return rule;
}
public void setRule(final Validate rule) {
this.rule = rule;
}
final public Input<?> getOther() {
return other;
}
/**
* Get the value of this input -- not to be called from operators!!!
* If this is a StateNode input, instead of returning
* the actual value, the current value of the StateNode
* is returned. This is defined as the current StateNode
* in the State, or itself if it is not part of the state.
*
* @return value of this input
*/
public T get() {
return value;
}
/**
* As get() but with this difference that the State can manage
* whether to make a copy and register the operator.
* <p/>
* Only Operators should call this method.
* Also Operators should never call Input.get(), always Input.get(operator).
*
* @param operator
* @return
*/
@SuppressWarnings("unchecked")
public T get(final Operator operator) {
return (T) ((StateNode) value).getCurrentEditable(operator);
}
/**
* Return the dirtiness state for this input.
* For a StateNode or list of StateNodes, report whether for any something is dirty,
* for a CalcationNode or list of CalculationNodes, report whether any is dirty.
* Otherwise, return false.
* *
*/
public boolean isDirty() {
final T value = get();
if (value == null) {
return false;
}
if (value instanceof StateNode) {
return ((StateNode) value).somethingIsDirty();
}
if (value instanceof CalculationNode) {
return ((CalculationNode) value).isDirtyCalculation();
}
if (value instanceof List<?>) {
for (final Object obj : (List<?>) value) {
if (obj instanceof CalculationNode && ((CalculationNode) obj).isDirtyCalculation()) {
return true;
} else if (obj instanceof StateNode && ((StateNode) obj).somethingIsDirty()) {
return true;
}
}
}
return false;
}
/**
* Sets value to this input.
* If class is not determined yet, first determine class of declaration of
* this input so that we can do type checking.
* If value is of type String, try to parse the value if this input is
* Integer, Double or Boolean.
* If this input is a List, instead of setting this value, the value is
* added to the vector.
* Otherwise, m_value is assigned to value.
*
* @param value
* @param plugin
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void setValue(final Object value, final BEASTInterface plugin) {
if (value == null) {
if (this.value != null) {
if (this.value instanceof BEASTInterface) {
((BEASTInterface) this.value).getOutputs().remove(plugin);
}
}
this.value = null;
return;
}
if (theClass == null) {
try {
determineClass(plugin);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to determine class of beastobject id=" + plugin.getID());
}
}
if (value instanceof String) {
try {
setStringValue((String) value, plugin);
} catch (Exception e) {
e.printStackTrace();
Log.warning.println("Failed to set the string value to '" + value + "' for beastobject id=" + plugin.getID());
throw new RuntimeException("Failed to set the string value to '" + value + "' for beastobject id=" + plugin.getID());
}
} else if (this.value != null && this.value instanceof List<?>) {
if (theClass.isAssignableFrom(value.getClass())) {
@SuppressWarnings("rawtypes") final
List vector = (List) this.value;
// // don't insert duplicates
// RRB: DO insert duplicates: this way CompoundValuable can be set up to
// contain rate matrices with dependent variables/parameters.
// There does not seem to be an example where a duplicate insertion is a problem...
// for (Object o : vector) {
// if (o.equals(value)) {
// return;
vector.add(value);
if (value instanceof BEASTInterface) {
((BEASTInterface) value).getOutputs().add(plugin);
}
} else if (value instanceof List<?> && theClass.isAssignableFrom(((List<?>) value).get(0).getClass())) {
// add all elements in given list to input list.
@SuppressWarnings("rawtypes")
final List<Object> vector = (List) this.value;
for (Object v : ((List<?>) value)) {
vector.add(v);
if (v instanceof BEASTInterface) {
((BEASTInterface) v).getOutputs().add(plugin);
}
}
} else {
throw new RuntimeException("Input 101: type mismatch for input " + getName() +
". " + theClass.getName() + ".isAssignableFrom(" + value.getClass() + ")=false");
}
} else {
if (theClass.isAssignableFrom(value.getClass())) {
if (value instanceof BEASTInterface) {
if (this.value != null) {
((BEASTInterface) this.value).getOutputs().remove(plugin);
}
((BEASTInterface) value).getOutputs().add(plugin);
}
this.value = (T) value;
} else {
throw new RuntimeException("Input 102: type mismatch for input " + getName());
}
}
}
/**
* Call custom input validation.
* For an input with name "name", the method canSetName will be invoked,
* that is, 'canSet' + the name of the input with first letter capitalised.
* The canSetName(Object o) method should have one argument of type Object.
* <p/>
* It is best for Beauti to throw an Exception from canSetName() with some
* diagnostic info when the value cannot be set.
*/
public boolean canSetValue(Object value, BEASTInterface plugin) {
String inputName = new String(name.charAt(0) + "").toUpperCase() + name.substring(1);
try {
Method method = plugin.getClass().getMethod("canSet" + inputName, Object.class);
//System.err.println("Calling method " + plugin.getClass().getName() +"."+ method.getName());
Object o = method.invoke(plugin, value);
return (Boolean) o;
} catch (java.lang.NoSuchMethodException e) {
return true;
} catch (java.lang.reflect.InvocationTargetException e) {
System.err.println(plugin.getClass().getName() + "." + getName() + ": " + e.getCause());
if (e.getCause() != null) {
throw new RuntimeException(e.getCause().getMessage());
}
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException("Illegal method access attempted on beastobject id=" + plugin.getID());
}
}
/**
* Determine class through introspection,
* This sets the theClass member of Input<T> to the actual value of T.
* If T is a vector, i.e. Input<List<S>>, the actual value of S
* is assigned instead
*
* @param plugin whose type is to be determined
* @throws Exception
*/
public void determineClass(final Object plugin) throws Exception {
try {
final Field[] fields = plugin.getClass().getFields();
// find this input in the plugin
for (int i = 0; i < fields.length; i++) {
if (fields[i].getType().isAssignableFrom(Input.class)) {
final Input<?> input = (Input<?>) fields[i].get(plugin);
if (input == this) {
// found the input, now determine the type of the input
Type t = fields[i].getGenericType();
Type[] genericTypes = ((ParameterizedType) t).getActualTypeArguments();
// check if it is a List
// NB: if the List is not initialised, there is no way
// to determine the type (that I know of...)
if (value != null && value instanceof List<?>) {
Type[] genericTypes2 = ((ParameterizedType) genericTypes[0]).getActualTypeArguments();
theClass = (Class<?>) genericTypes2[0];
// gettting type of map is not possible?!?
//} else if (value != null && value instanceof Map<?,?>) {
// Type[] genericTypes2 = ((ParameterizedType) genericTypes[0]).getActualTypeArguments();
// theClass = (Class<?>) genericTypes2[0];
} else {
// it is not a list (or if it is, this will fail)
try {
Object o = genericTypes[0];
if (o instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) genericTypes[0]).getRawType();
System.err.println(rawType.getTypeName());
if (rawType.getTypeName().equals("java.util.List")) {
// if we got here, value==null
throw new Exception("Programming error: Input<List> not initialised");
}
}
theClass = (Class<?>) o;
} catch (Exception e) {
// resolve ID
String id = "";
Method method = plugin.getClass().getMethod("getID");
if (method != null) {
id = (String) method.invoke(plugin);
}
// assemble error message
System.err.println(plugin.getClass().getName() + " " + id + " failed. " +
"Possibly template or abstract Plugin used " +
"or if it is a list, the list was not initilised???");
System.err.println("class is " + plugin.getClass());
e.printStackTrace(System.err);
System.exit(0);
}
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} // determineClass
/**
* Try to parse value of string into Integer, Double or Boolean,
* or it this types differs, just assign as string.
*
* @param sValue value representation
* @throws Exception when all conversions fail
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void setStringValue(final String sValue, final BEASTInterface plugin) throws Exception {
// figure out the type of T and create object based on T=Integer, T=Double, T=Boolean, T=Valuable
if (value instanceof List<?>) {
List list = (List) value;
list.clear();
// remove start and end spaces
String sValue2 = sValue.replaceAll("^\\s+", "");
sValue2 = sValue2.replaceAll("\\s+$", "");
// split into space-separated bits
String[] sValues = sValue2.split("\\s+");
for (int i = 0; i < sValues.length; i++) {
if (theClass.equals(Integer.class)) {
list.add(new Integer(sValues[i % sValues.length]));
} else if (theClass.equals(Double.class)) {
list.add(new Double(sValues[i % sValues.length]));
} else if (theClass.equals(Boolean.class)) {
String str = sValues[i % sValues.length].toLowerCase();
list.add(str.equals("1") || str.equals("true") || str.equals("yes"));
} else if (theClass.equals(String.class)) {
list.add(new String(sValues[i % sValues.length]));
}
}
return;
}
if (theClass.equals(Integer.class)) {
value = (T) new Integer(sValue);
return;
}
if (theClass.equals(Double.class)) {
value = (T) new Double(sValue);
return;
}
if (theClass.equals(Boolean.class)) {
final String sValue2 = sValue.toLowerCase();
if (sValue2.equals("yes") || sValue2.equals("true")) {
value = (T) Boolean.TRUE;
return;
} else if (sValue2.equals("no") || sValue2.equals("false")) {
value = (T) Boolean.FALSE;
return;
}
}
if (theClass.equals(Function.class)) {
final RealParameter param = new RealParameter();
param.initByName("value", sValue, "upper", 0.0, "lower", 0.0, "dimension", 1);
param.initAndValidate();
if (value != null && value instanceof List) {
((List) value).add(param);
} else {
value = (T) param;
}
param.getOutputs().add(plugin);
return;
}
if (theClass.isEnum()) {
if (possibleValues == null) {
possibleValues = (T[]) theClass.getDeclaringClass().getEnumConstants();
}
for (final T t : possibleValues) {
if (sValue.equals(t.toString())) {
value = t;
return;
}
}
throw new Exception("Input 104: value " + sValue + " not found. Select one of " + Arrays.toString(possibleValues));
}
// call a string constructor of theClass
try {
Constructor ctor;
Object v = sValue;
try {
ctor = theClass.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException e) {
// we get here if there is not String constructor
// try integer constructor instead
try {
if (sValue.startsWith("0x")) {
v = Integer.parseInt(sValue.substring(2), 16);
} else {
v = Integer.parseInt(sValue);
}
ctor = theClass.getDeclaredConstructor(int.class);
} catch (NumberFormatException e2) {
// could not parse as integer, try double instead
v = Double.parseDouble(sValue);
ctor = theClass.getDeclaredConstructor(double.class);
}
}
ctor.setAccessible(true);
final Object o = ctor.newInstance(v);
if (value != null && value instanceof List) {
((List) value).add(o);
} else {
value = (T) o;
}
if (o instanceof BEASTInterface) {
((BEASTInterface) o).getOutputs().add(plugin);
}
} catch (Exception e) {
throw new Exception("Input 103: type mismatch, cannot initialize input '" + getName() +
"' with value '" + sValue + "'.\nExpected something of type " + getType().getName() +
". " + (e.getMessage() != null ? e.getMessage() : ""));
}
} // setStringValue
/**
* validate input according to validation rule *
*
* @throws Exception when validation fails. why not return a string?
*/
public void validate() throws Exception {
if (possibleValues != null) {
// it is an enumeration, check the value is in the list
boolean bFound = false;
for (final T value : possibleValues) {
if (value.equals(this.value)) {
bFound = true;
}
}
if (!bFound) {
throw new Exception("Expected one of " + Arrays.toString(possibleValues) + " but got " + this.value);
}
}
switch (rule) {
case OPTIONAL:
// noting to do
break;
case REQUIRED:
if (get() == null) {
throw new Exception("Input '" + getName() + "' must be specified.");
}
if (get() instanceof List<?>) {
if (((List<?>) get()).size() == 0) {
throw new Exception("At least one input of name '" + getName() + "' must be specified.");
}
}
break;
case XOR:
if (get() == null) {
if (other.get() == null) {
throw new Exception("Either input '" + getName() + "' or '" + other.getName() + "' needs to be specified");
}
} else {
if (other.get() != null) {
throw new Exception("Only one of input '" + getName() + "' and '" + other.getName() + "' must be specified (not both)");
}
}
// noting to do
break;
case FORBIDDEN:
if (get() instanceof List<?>) {
if (((List<?>) get()).size() > 0) {
throw new Exception("No input of name '" + getName() + "' must be specified.");
}
} else if (get() != null) {
throw new Exception("Input '" + getName() + "' must not be specified.");
}
break;
}
} // validate
} // class Input
|
package com.mirasense.scanditsdk.plugin;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.mirasense.scanditsdk.LegacyPortraitScanditSDKBarcodePicker;
import com.mirasense.scanditsdk.ScanditSDKBarcodePicker;
import com.mirasense.scanditsdk.ScanditSDKScanSettings;
import com.mirasense.scanditsdk.interfaces.*;
import com.mirasense.scanditsdk.interfaces.ScanditSDK;
import com.mirasense.scanditsdk.internal.ScanditSDKGlobals;
public class ScanditSDKParameterParser {
public static final String paramAppKey = "appKey".toLowerCase();
public static final String paramContinuousMode = "continuousMode".toLowerCase();
public static final String paramPortraitMargins = "portraitMargins".toLowerCase();
public static final String paramLandscapeMargins = "landscapeMargins".toLowerCase();
public static final String paramAnimationDuration = "animationDuration".toLowerCase();
public static final String paramPreferFrontCamera = "preferFrontCamera".toLowerCase();
public static final String param1DScanning = "1DScanning".toLowerCase();
public static final String param2DScanning = "2DScanning".toLowerCase();
public static final String paramEan13AndUpc12 = "ean13AndUpc12".toLowerCase();
public static final String paramEan8 = "ean8".toLowerCase();
public static final String paramUpce = "upce".toLowerCase();
public static final String paramCode39 = "code39".toLowerCase();
public static final String paramCode93 = "code93".toLowerCase();
public static final String paramCode128 = "code128".toLowerCase();
public static final String paramItf = "itf".toLowerCase();
public static final String paramGS1Databar = "gs1Databar".toLowerCase();
public static final String paramGS1DatabarExpanded = "gs1DatabarExpanded".toLowerCase();
public static final String paramCodabar = "codabar".toLowerCase();
public static final String paramQR = "qr".toLowerCase();
public static final String paramDatamatrix = "datamatrix".toLowerCase();
public static final String paramPdf417 = "pdf417".toLowerCase();
public static final String paramAztec = "aztec".toLowerCase();
public static final String paramMsiPlessey = "msiPlessey".toLowerCase();
public static final String paramMsiPlesseyChecksumType = "msiPlesseyChecksumType".toLowerCase();
public static final String paramMsiPlesseyChecksumTypeNone = "none".toLowerCase();
public static final String paramMsiPlesseyChecksumTypeMod11 = "mod11".toLowerCase();
public static final String paramMsiPlesseyChecksumTypeMod1010 = "mod1010".toLowerCase();
public static final String paramMsiPlesseyChecksumTypeMod1110 = "mod1110".toLowerCase();
public static final String paramInverseRecognition = "inverseRecognition".toLowerCase();
public static final String paramMicroDataMatrix = "microDataMatrix".toLowerCase();
public static final String paramForce2D = "force2d".toLowerCase();
public static final String paramCodeDuplicateFilter = "codeDuplicateFilter".toLowerCase();
public static final String paramScanningHotSpot = "scanningHotSpot".toLowerCase();
public static final String paramScanningHotSpotHeight = "scanningHotSpotHeight".toLowerCase();
public static final String paramSearchBar = "searchBar".toLowerCase();
public static final String paramBeep = "beep".toLowerCase();
public static final String paramVibrate = "vibrate".toLowerCase();
public static final String paramTorch = "torch".toLowerCase();
public static final String paramTorchButtonPositionAndSize = "torchButtonPositionAndSize".toLowerCase();
public static final String paramCameraSwitchVisibility = "cameraSwitchVisibility".toLowerCase();
public static final String paramCameraSwitchVisibilityTablet = "tablet".toLowerCase();
public static final String paramCameraSwitchVisibilityAlways = "always".toLowerCase();
public static final String paramCameraSwitchButtonPositionAndSize = "cameraSwitchButtonPositionAndSize".toLowerCase();
public static final String paramSearchBarPlaceholderText = "searchBarPlaceholderText".toLowerCase();
public static final String paramViewfinder = "viewfinder".toLowerCase();
public static final String paramViewfinderDimension = "viewfinderDimension".toLowerCase();
public static final String paramViewfinderSize = "viewfinderSize".toLowerCase();
public static final String paramViewfinderTextHook = "viewfinderTextHook".toLowerCase();
public static final String paramViewfinderColor = "viewfinderColor".toLowerCase();
public static final String paramViewfinderDecodedColor = "viewfinderDecodedColor".toLowerCase();
public static final String paramLogoOffsets = "logoOffsets".toLowerCase();
public static final String paramZoom = "zoom".toLowerCase();
public static final String paramGuiStyle = "guiStyle".toLowerCase();
public static final String paramGuiStyleLaser = "laser".toLowerCase();
public static ScanditSDKScanSettings settingsForBundle(Bundle bundle) {
ScanditSDKScanSettings settings = ScanditSDKScanSettings.getDefaultSettings();
int facing = ScanditSDK.CAMERA_FACING_BACK;
if (bundle.containsKey(paramPreferFrontCamera) && bundle.getBoolean(paramPreferFrontCamera)) {
facing = ScanditSDK.CAMERA_FACING_FRONT;
}
settings.setCameraFacingPreference(facing);
if (bundle.containsKey(param1DScanning) && bundle.getBoolean(param1DScanning)) {
Log.e("ScanditSDK", "The parameter '1DScanning' is deprecated. Please enable symbologies individually instead");
settings.enableSymbologies(new ScanditSDK.Symbology[]{
ScanditSDK.Symbology.EAN13, ScanditSDK.Symbology.UPC12, ScanditSDK.Symbology.EAN8,
ScanditSDK.Symbology.CODE128, ScanditSDK.Symbology.CODE39, ScanditSDK.Symbology.CODE93,
ScanditSDK.Symbology.ITF, ScanditSDK.Symbology.MSI_PLESSEY, ScanditSDK.Symbology.UPCE,
ScanditSDK.Symbology.CODABAR, ScanditSDK.Symbology.GS1_DATABAR,
ScanditSDK.Symbology.GS1_DATABAR_EXPANDED});
}
if (bundle.containsKey(param2DScanning) && bundle.getBoolean(param2DScanning)) {
Log.e("ScanditSDK", "The parameter '2DScanning' is deprecated. Please enable symbologies individually instead");
settings.enableSymbologies(new ScanditSDK.Symbology[]{
ScanditSDK.Symbology.AZTEC, ScanditSDK.Symbology.DATAMATRIX, ScanditSDK.Symbology.PDF417,
ScanditSDK.Symbology.QR});
}
if ((bundle.containsKey(paramEan13AndUpc12) && bundle.getBoolean(paramEan13AndUpc12))
|| !bundle.containsKey(paramEan13AndUpc12)) {
//Log.e("ScanditSDK", "The parameter 'ean13AndUpc12' is deprecated. Please enable the symbologies individually instead");
settings.enableSymbology(ScanditSDK.Symbology.EAN13);
settings.enableSymbology(ScanditSDK.Symbology.UPC12);
}
if ((bundle.containsKey(paramEan8) && bundle.getBoolean(paramEan8))
|| !bundle.containsKey(paramEan8)) {
settings.enableSymbology(ScanditSDK.Symbology.EAN8);
}
if ((bundle.containsKey(paramUpce) && bundle.getBoolean(paramUpce))
|| !bundle.containsKey(paramUpce)) {
settings.enableSymbology(ScanditSDK.Symbology.UPCE);
}
if ((bundle.containsKey(paramCode39) && bundle.getBoolean(paramCode39))
|| !bundle.containsKey(paramCode39)) {
settings.enableSymbology(ScanditSDK.Symbology.CODE39);
}
if ((bundle.containsKey(paramCode93) && bundle.getBoolean("code93"))
|| !bundle.containsKey(paramCode93)) {
settings.enableSymbology(ScanditSDK.Symbology.CODE93);
}
if ((bundle.containsKey(paramCode128) && bundle.getBoolean(paramCode128))
|| !bundle.containsKey(paramCode128)) {
settings.enableSymbology(ScanditSDK.Symbology.CODE128);
}
if (bundle.containsKey(paramItf) && bundle.getBoolean(paramItf)) {
settings.enableSymbology(ScanditSDK.Symbology.ITF);
}
if (bundle.containsKey(paramGS1Databar) && bundle.getBoolean(paramGS1Databar)) {
settings.enableSymbology(ScanditSDK.Symbology.GS1_DATABAR);
}
if (bundle.containsKey(paramGS1DatabarExpanded) && bundle.getBoolean(paramGS1DatabarExpanded)) {
settings.enableSymbology(ScanditSDK.Symbology.GS1_DATABAR_EXPANDED);
}
if (bundle.containsKey(paramCodabar) && bundle.getBoolean(paramCodabar)) {
settings.enableSymbology(ScanditSDK.Symbology.CODABAR);
}
if ((bundle.containsKey(paramQR) && bundle.getBoolean(paramQR))
|| !bundle.containsKey(paramQR)) {
settings.enableSymbology(ScanditSDK.Symbology.QR);
}
if ((bundle.containsKey(paramDatamatrix) && bundle.getBoolean(paramDatamatrix))
|| !bundle.containsKey(paramDatamatrix)) {
settings.enableSymbology(ScanditSDK.Symbology.DATAMATRIX);
}
if (bundle.containsKey(paramPdf417) && bundle.getBoolean(paramPdf417)) {
settings.enableSymbology(ScanditSDK.Symbology.PDF417);
}
if (bundle.containsKey(paramAztec) && bundle.getBoolean(paramAztec)) {
settings.enableSymbology(ScanditSDK.Symbology.AZTEC);
}
if (bundle.containsKey(paramMsiPlessey) && bundle.getBoolean(paramMsiPlessey)) {
settings.enableSymbology(ScanditSDK.Symbology.MSI_PLESSEY);
}
if (bundleContainsStringKey(bundle, paramMsiPlesseyChecksumType)) {
String checksum = bundle.getString(paramMsiPlesseyChecksumType);
int actualChecksum = com.mirasense.scanditsdk.interfaces.ScanditSDK.CHECKSUM_MOD_10;
if (checksum.equals(paramMsiPlesseyChecksumTypeNone)) {
actualChecksum = com.mirasense.scanditsdk.interfaces.ScanditSDK.CHECKSUM_NONE;
} else if (checksum.equals(paramMsiPlesseyChecksumTypeMod11)) {
actualChecksum = com.mirasense.scanditsdk.interfaces.ScanditSDK.CHECKSUM_MOD_11;
} else if (checksum.equals(paramMsiPlesseyChecksumTypeMod1010)) {
actualChecksum = com.mirasense.scanditsdk.interfaces.ScanditSDK.CHECKSUM_MOD_1010;
} else if (checksum.equals(paramMsiPlesseyChecksumTypeMod1110)) {
actualChecksum = com.mirasense.scanditsdk.interfaces.ScanditSDK.CHECKSUM_MOD_1110;
}
settings.setMsiPlesseyChecksumType(actualChecksum);
}
if (bundle.containsKey(paramInverseRecognition)) {
settings.enableColorInverted2dRecognition(bundle.getBoolean(paramInverseRecognition));
}
if (bundle.containsKey(paramMicroDataMatrix)) {
settings.enableMicroDataMatrix(bundle.getBoolean(paramMicroDataMatrix));
}
if (bundle.containsKey(paramForce2D)) {
settings.force2dRecognition(bundle.getBoolean(paramForce2D));
}
if (bundle.containsKey(paramCodeDuplicateFilter)) {
settings.setCodeDuplicateFilter(bundle.getInt(paramCodeDuplicateFilter));
}
if (bundleContainsStringKey(bundle, paramScanningHotSpot)) {
String hotspot = bundle.getString(paramScanningHotSpot);
String[] split = hotspot.split("[/]");
if (split.length == 2) {
try {
Float x = Float.valueOf(split[0]);
Float y = Float.valueOf(split[1]);
settings.setScanningHotSpot(x, y);
} catch (NumberFormatException e) {}
}
}
if (bundle.containsKey(paramScanningHotSpotHeight)) {
settings.enableRestrictedAreaScanning(true);
settings.setScanningHotSpotHeight((float) bundle.getDouble(paramScanningHotSpotHeight));
}
return settings;
}
public static void updatePickerUIFromBundle(ScanditSDK picker, Bundle bundle) {
if (bundle.containsKey(paramSearchBar)) {
picker.getOverlayView().showSearchBar(bundle.getBoolean(paramSearchBar));
}
if (bundle.containsKey(paramBeep)) {
picker.getOverlayView().setBeepEnabled(bundle.getBoolean(paramBeep));
}
if (bundle.containsKey(paramVibrate)) {
picker.getOverlayView().setVibrateEnabled(bundle.getBoolean(paramVibrate));
}
if (bundle.containsKey(paramTorch)) {
picker.getOverlayView().setTorchEnabled(bundle.getBoolean(paramTorch));
}
if (bundleContainsStringKey(bundle, paramTorchButtonPositionAndSize)) {
String hotspot = bundle.getString(paramTorchButtonPositionAndSize);
String[] split = hotspot.split("[/]");
if (split.length == 4) {
try {
Float x = Float.valueOf(split[0]);
Float y = Float.valueOf(split[1]);
int width = Integer.valueOf(split[2]);
int height = Integer.valueOf(split[3]);
picker.getOverlayView().setTorchButtonPosition(x, y, width, height);
} catch (NumberFormatException e) {}
}
}
if (bundleContainsStringKey(bundle, paramCameraSwitchVisibility)) {
String visibility = bundle.getString(paramCameraSwitchVisibility);
int actualVisibility = ScanditSDKOverlay.CAMERA_SWITCH_NEVER;
if (visibility.equals(paramCameraSwitchVisibilityTablet)) {
actualVisibility = ScanditSDKOverlay.CAMERA_SWITCH_ON_TABLET;
} else if (visibility.equals(paramCameraSwitchVisibilityAlways)) {
actualVisibility = ScanditSDKOverlay.CAMERA_SWITCH_ALWAYS;
}
picker.getOverlayView().setCameraSwitchVisibility(actualVisibility);
}
if (bundleContainsStringKey(bundle, paramCameraSwitchButtonPositionAndSize)) {
String hotspot = bundle.getString(paramCameraSwitchButtonPositionAndSize);
String[] split = hotspot.split("[/]");
if (split.length == 4) {
try {
Float x = Float.valueOf(split[0]);
Float y = Float.valueOf(split[1]);
int width = Integer.valueOf(split[2]);
int height = Integer.valueOf(split[3]);
picker.getOverlayView().setCameraSwitchButtonPosition(
x, y, width, height);
} catch (NumberFormatException e) {}
}
}
if (bundleContainsStringKey(bundle, paramSearchBarPlaceholderText)) {
picker.getOverlayView().setSearchBarPlaceholderText(
bundle.getString(paramSearchBarPlaceholderText));
}
if (bundleContainsStringKey(bundle, paramViewfinderDimension)
|| bundleContainsStringKey(bundle, paramViewfinderSize)) {
String hotspot = "";
if (bundle.containsKey(paramViewfinderDimension)) {
hotspot = bundle.getString(paramViewfinderDimension);
} else if (bundle.containsKey(paramViewfinderSize)) {
hotspot = bundle.getString(paramViewfinderSize);
}
String[] split = hotspot.split("[/]");
if (split.length == 2) {
try {
Float width = Float.valueOf(split[0]);
Float height = Float.valueOf(split[1]);
picker.getOverlayView().setViewfinderDimension(width, height);
} catch (NumberFormatException e) {}
} else if (split.length == 4) {
try {
Float width = Float.valueOf(split[0]);
Float height = Float.valueOf(split[1]);
Float landscapeWidth = Float.valueOf(split[2]);
Float landscapeHeight = Float.valueOf(split[3]);
picker.getOverlayView().setViewfinderDimension(
width, height, landscapeWidth, landscapeHeight);
} catch (NumberFormatException e) {}
}
}
if (bundleContainsStringKey(bundle, paramViewfinderColor)) {
String color = bundle.getString(paramViewfinderColor);
if (color.length() == 6) {
try {
String red = color.substring(0, 2);
String green = color.substring(2, 4);
String blue = color.substring(4, 6);
float r = ((float) Integer.parseInt(red, 16)) / 256.0f;
float g = ((float) Integer.parseInt(green, 16)) / 256.0f;
float b = ((float) Integer.parseInt(blue, 16)) / 256.0f;
picker.getOverlayView().setViewfinderColor(r, g, b);
} catch (NumberFormatException e) {}
}
}
if (bundleContainsStringKey(bundle, paramViewfinderDecodedColor)) {
String color = bundle.getString(paramViewfinderDecodedColor);
if (color.length() == 6) {
try {
String red = color.substring(0, 2);
String green = color.substring(2, 4);
String blue = color.substring(4, 6);
float r = ((float) Integer.parseInt(red, 16)) / 256.0f;
float g = ((float) Integer.parseInt(green, 16)) / 256.0f;
float b = ((float) Integer.parseInt(blue, 16)) / 256.0f;
picker.getOverlayView().setViewfinderDecodedColor(r, g, b);
} catch (NumberFormatException e) {}
}
}
if (bundle.containsKey(paramViewfinder)) {
picker.getOverlayView().drawViewfinder(bundle.getBoolean(paramViewfinder));
}
if (bundleContainsStringKey(bundle, paramLogoOffsets)) {
String offsets = bundle.getString(paramLogoOffsets);
String[] split = offsets.split("[,]");
if (split.length == 4) {
try {
Float xOffset = Float.valueOf(split[0].trim());
Float yOffset = Float.valueOf(split[1].trim());
Float landscapeXOffset = Float.valueOf(split[2].trim());
Float landscapeYOffset = Float.valueOf(split[3].trim());
picker.getOverlayView().setViewfinderDimension(
xOffset, yOffset, landscapeXOffset, landscapeYOffset);
} catch (NumberFormatException e) {}
}
}
if (bundle.containsKey(paramZoom)) {
picker.setZoom(bundle.getFloat(paramZoom));
}
if (bundleContainsStringKey(bundle, paramGuiStyle)) {
String guiStyle = bundle.getString(paramGuiStyle);
if (guiStyle.equals(paramGuiStyleLaser)) {
picker.getOverlayView().setGuiStyle(ScanditSDKOverlay.GUI_STYLE_LASER);
} else {
picker.getOverlayView().setGuiStyle(ScanditSDKOverlay.GUI_STYLE_DEFAULT);
}
}
}
private static boolean bundleContainsStringKey(Bundle bundle, String key) {
return (bundle.containsKey(key) && bundle.getString(key) != null);
}
}
|
package jlibs.nbp;
import java.io.IOException;
import java.nio.charset.CoderResult;
import static java.lang.Character.*;
/**
* @author Santhosh Kumar T
*/
public abstract class NBParser{
private final Stream stream;
protected final Stream.LookAhead lookAhead;
public final Location location = new Location();
protected final Buffer buffer = new Buffer();
private int startingRule;
public NBParser(int maxLookAhead, int startingRule){
stream = new Stream(maxLookAhead);
lookAhead = stream.lookAhead;
reset(startingRule);
}
public void reset(int rule){
wasHighSurrogate = false;
stream.clear();
location.reset();
buffer.clear();
ruleStack.clear();
stateStack.clear();
ruleStack.push(startingRule=rule);
stateStack.push(0);
}
public void reset(){
reset(startingRule);
}
private char highSurrogate;
private boolean wasHighSurrogate;
public void consume(char ch) throws IOException{
if(wasHighSurrogate){
wasHighSurrogate = false;
if(ch>=MIN_LOW_SURROGATE && ch<=MAX_LOW_SURROGATE)
consume(((highSurrogate - MIN_HIGH_SURROGATE) << 10) + (ch - MIN_LOW_SURROGATE) + MIN_SUPPLEMENTARY_CODE_POINT);
else
ioError("bad surrogate pair");
}else if(ch>=MIN_HIGH_SURROGATE && ch<=MAX_HIGH_SURROGATE){
highSurrogate = ch;
wasHighSurrogate = true;
}else
consume((int)ch);
}
public void consume(int codePoint) throws IOException{
try{
consumed = false;
_eat(codePoint);
if(!consumed && stream.length()==0)
consumed(codePoint);
while(lookAhead.hasNext()){
consumed = false;
int lookAheadLen = lookAhead.length();
_eat(lookAhead.getNext());
if(!consumed && lookAhead.length()==lookAheadLen)
consumed();
}
}catch(IOException ex){
throw ex;
}catch(Exception ex){
if(ex.getCause() instanceof IOException)
throw (IOException)ex.getCause();
else
throw new IOException(ex);
}
}
private void _eat(int ch) throws Exception{
while(true){
if(stateStack.isEmpty()){
if(ch==-1){
onSuccessful();
return;
}else
expected(ch, "<EOF>");
}
int state = callRule(ch);
if(state==-1){
pop();
if(lookAhead.length()>0){
lookAhead.reset();
return;
}
}else{
stateStack.setPeek(state);
break;
}
}
}
protected abstract int callRule(int ch) throws Exception;
protected void expected(int ch, String... matchers) throws Exception{
String found;
if(stream.length()>0)
found = stream.toString();
else{
if(ch==-1)
found = "<EOF>";
else
found = new String(toChars(ch));
}
StringBuilder buff = new StringBuilder();
for(String matcher: matchers){
if(buff.length()>0)
buff.append(" OR ");
buff.append(matcher);
}
String message = "Found: '"+found+"' Expected: "+buff.toString();
fatalError(message);
throw new IOException(message);
}
protected abstract void fatalError(String message) throws Exception;
protected abstract void onSuccessful() throws Exception;
protected void consumed(){
int ch = stream.charAt(0);
if(ch!=-1)
consumed(ch);
lookAhead.consumed();
}
protected boolean consumed = false;
protected void consumed(int ch){
consumed = true;
location.consume(ch);
if(buffer.isBufferring())
buffer.append(ch);
}
protected final IntStack ruleStack = new IntStack();
protected final IntStack stateStack = new IntStack();
protected void push(int toRule, int stateAfterRule, int stateInsideRule){
stateStack.setPeek(stateAfterRule);
ruleStack.push(toRule);
stateStack.push(stateInsideRule);
}
protected void pop(){
ruleStack.pop();
stateStack.pop();
}
public void encodingError(CoderResult coderResult) throws IOException{
ioError(coderResult.isMalformed() ? "Malformed Input" : "Unmappable Character");
}
protected void ioError(String message) throws IOException{
try{
fatalError(message);
throw new IOException(message);
}catch(Exception ex){
throw new IOException(message);
}
}
}
|
package am.app.ontology;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.impl.OntResourceImpl;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.sun.xml.internal.bind.v2.runtime.output.Pcdata;
import am.app.Core;
import am.app.mappingEngine.AbstractMatcher.alignType;
import am.userInterface.ontology.OntologyConceptGraphics;
import am.userInterface.vertex.*;
import am.utility.Pair;
/**
* This class represents an element of the ontology to be aligned.
* we could use the Resource class of Jena directly, but accessing information would be slower
* so we use our own structure, even though we keep the reference to the Jena structure
*
*/
public class Node {
/** This is the reference of the Resource in the ontology, this is a Jena class.
* When parsing an XML ontology, there will be a Jena OntModel built in order to provide this resource.
* The Node object is built taking information from this Jena Resource.
* If we have loaded an OWL ontology this resource will be instance of OntResource.
* If this node is a ClassNode, the resource will be instance of OntClass.
* The Jena Resource is used to access all information in the ontology regarding this concept.
*/
private Resource resource;
/** The OWL/RDF uri identifier, that is namespace#localname.
* This info is kept in the resource variable but we keep them separate to access them easily. TODO - Should we really be duplicating this information? - Cosmin.
*/
private String uri = "";
/**
* One of the string which can be used to compare two nodes
* In general the URI = namespace#localname, in the OWL ontology, often the localname is the same of label
* usually is defined with rdf: ID */
protected String localName = ""; // TODO - Avoid duplication of information. The localname can be gotten from the Jena Resource. - Cosmin.
/**
* Another string which can be used to compare nodes
* This should be a human readable version of localname. In a RDF or XML ontologies there are no labels
* In OWL ontology we can have a label, even though often is the same of name.
* rdfs:label
*/
private String label = ""; // TODO - Avoid duplication of information. The label can be gotten from the Jena Resource. - Cosmin.
/**
* Another string which can be used to compare nodes
* This is a longer description (more than one word) for this resource.In a RDF or XML ontologies there are no comments
* In OWL ontology we can have a comment.
* rdfs:comment
*/
private String comment = ""; // TODO - Avoid duplication of information. The comment can be gotten from the Jena Resource. - Cosmin.
//SOME MORE INFORMATIONS THAT MY BE USED -- // TODO - Avoid duplication of information. All the info can be gotten from the Jena Resource. - Cosmin.
private String isDefinedByLabel = "";
private String isDefinedByURI = "";
private String isDefinedByComment = "";
private String seeAlsoLabel = "";
private String seeAlsoURI = "";
private String seeAlsoComment = "";
/** If the node is a prop node then it this list contains the list of classes localnames which declare this property.
If the node is a class node then this list contains the list of properties declared by this class.
*/
private ArrayList<String> propOrClassNeighbours = new ArrayList<String>();
/**
* A list of the individuals associated with this node.
*/
private ArrayList<String> individuals = new ArrayList<String>();
/**
* A Class or Property in a OWL hierarchy may have more than one father. In this case all nodes in the subtree of the node with more fathes will be represented with duplicates in the hierarchy tree
* but it will be aligned only once. We won't be able to access the vertex of this node with getVertex(), because this node is represetend by more than one vertex
* so we will have to scan a the list of vertex of this node, unless we want to access any of his vertex.
*List of vertex representing the node in the graphical tree hierarchy
* Usually each node is represeted only by one vertex, but if the node hasDuplicate, it's represented more times
*/
private ArrayList<Vertex> vertexList = new ArrayList<Vertex>();
/**RDF-node, OWL-classnode, OWL-propnode, OWL-unsatconcept, XML-node*/
private String type;
public final static String RDFNODE = "rdf-node";
public final static String OWLCLASS = "owl-classnode";
public final static String OWLPROPERTY = "owl-propertynode";
public final static String XMLNODE = "xml-node";
/**UNIQUE KEY IN THE RANGE OF TYPE to be used as index to retrieve this node from the list and from the matrix*/
protected int index;
protected int ontindex; // the index of the ONTOLOGY to which this node belongs
private int color;
private ArrayList<Node> parent = new ArrayList<Node>();
private int depth;
/**
* This is an arraylist all the graphical representations of this node.
* This must be a list, as opposed to a single variable, because AgreementMaker
* can have multiple graphical representations of the same ontology.
*/
private ArrayList<OntologyConceptGraphics> graphicalRepresentations = new ArrayList<OntologyConceptGraphics>();
/**
* XML constructor
* @param key
* @param name
* @param desc
* @param type
*/
public Node(int key, String name, String type, int oindex) {
localName = name;
this.type = type;
index = key;
ontindex = oindex;
}
public Node(Node a){
localName = a.localName;
type = a.type;
index = a.index;
String language = "EN";
resource = a.resource;
uri = a.getUri();
localName = a.getLocalName();
vertexList.addAll(a.getVertexList());
ontindex = a.ontindex;
}
/**RDF OWL Constructor*/
public Node(int key, Resource r, String type, int oindex ) {
String language = "EN";
resource = r;
uri = r.getURI();
localName = r.getLocalName();
ontindex = oindex;
this.type = type;
if(r.canAs(OntResource.class)) {
OntResource or = (OntResource)r.as(OntResource.class);
// Set the label. (Why are we duplicating this information?)
label = or.getLabel(language);
if(label == null || label == "")
label = or.getLabel(null);
if(label == null)
label = "";
//COmments
comment = "";
Literal l = null;
ExtendedIterator it = or.listComments(language);
if(!it.hasNext())
it = or.listComments(null);
while(it.hasNext()) {
l = (Literal)it.next();
if(l!=null) comment+= l+" ";
}
//ANNOTATIONS: isDefBy and seeAlso I'm not considering "sameAs" "differentFrom" "disjointWith"
it = or.listIsDefinedBy();
isDefinedByLabel = "";
isDefinedByURI = "";
isDefinedByComment = "";
l = null;
OntResource or2;
if(it.hasNext()) {
RDFNode ol = (RDFNode) it.next();
//OntResourceImpl ol = (OntResourceImpl)it.next();
if(ol!= null && ol.canAs(OntResource.class)){
or2 = (OntResource)ol.as(OntResource.class);
isDefinedByLabel = or2.getLabel(language);
if(isDefinedByLabel == null || isDefinedByLabel == "")
isDefinedByLabel = or2.getLabel(null);
if(isDefinedByLabel == null)
isDefinedByLabel = "";
isDefinedByComment = or2.getComment(language);
if(isDefinedByComment == null || isDefinedByComment == "")
isDefinedByComment = or2.getLabel(null);
if(isDefinedByComment == null)
isDefinedByComment = "";
isDefinedByURI = or2.getURI();
} else if( ol != null && ol.canAs(Literal.class) ) {
Literal l1 = (Literal) ol.as(Literal.class);
isDefinedByLabel = l1.toString();
}
}
it = or.listSeeAlso();
seeAlsoLabel = "";
seeAlsoComment = "";
seeAlsoURI = "";
l = null;
if(it.hasNext()) {
RDFNode ol = (RDFNode)it.next();
if(ol!= null && ol.canAs(OntResource.class)){
or2 = (OntResource)ol.as(OntResource.class);
seeAlsoLabel = or2.getLabel(language);
if(seeAlsoLabel == null || seeAlsoLabel == "")
seeAlsoLabel = or2.getLabel(null);
if(seeAlsoLabel == null)
seeAlsoLabel = "";
seeAlsoComment = or2.getComment(language);
if(seeAlsoComment == null || seeAlsoComment == "")
seeAlsoComment = or2.getLabel(null);
if(seeAlsoComment == null)
seeAlsoComment = "";
seeAlsoURI = or2.getURI();
} else if( ol != null && ol.canAs(Literal.class) ) {
Literal l1 = (Literal) ol.as(Literal.class);
seeAlsoLabel = l1.toString();
}
}
//properties and invidviduals lists only for classes
if(!or.canAs(OntProperty.class)) {//remember is important to check on prop instead of class to avoid a jena bug that a prop canAs ontClass
OntClass cls = (OntClass)or.as(OntClass.class);
it = cls.listDeclaredProperties(true);
String localname;
while(it.hasNext()) {
OntProperty op = (OntProperty)it.next();
if(!op.isAnon()) {
localname = op.getLocalName();
propOrClassNeighbours.add(localname);
}
}
it = cls.listInstances(true);
while(it.hasNext()) {
Individual ind = (Individual)it.next();
localname = ind.getLabel(null);
if(localname != null && !localname.equals(""))
individuals.add(localname);
}
}
else {
OntProperty prop = (OntProperty)or.as(OntProperty.class);
it = prop.listDeclaringClasses(true);
String localname;
while(it.hasNext()) {
OntClass op = (OntClass)it.next();
if(!op.isAnon()) {
localname = op.getLocalName();
propOrClassNeighbours.add(localname);
}
}
}
}
index = key;
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Deprecated
public boolean hasDuplicates() {
return vertexList.size() > 1;
}
public ArrayList<Vertex> getVertexList() {
return vertexList;
}
public void addVertex(Vertex v) {
vertexList.add(v);
}
public Vertex getVertex() {
if( vertexList != null && !vertexList.isEmpty() )
return vertexList.get(0);
else
return null;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
/**Owl classes or all rdf nodes or all xml nodes their are considered classes, so nodes in the first of the two trees*/
public boolean isClass() {
if( resource.canAs(OntClass.class)) return true;
return false;
}
public boolean isProp() {
if( resource.canAs(OntProperty.class) ) return true;
return false;
}
public boolean equals( Node o) {
/**
* For a node to be equal to a second node
* they must both be
* 1. of equal type (classes, properties, individuals )
* 2. of equal ontology ( source ontology nodes can only be equal with source ontology nodes, and the same for target ontology)
* 3. of equal index ( the index is unique, and if the other two points are equal, equality of indices will indicate equality )
*/
// 1. Equal Type
if( o.isProp() != isProp() ) return false;
if( o.isClass() != isClass() ) return false;
// 2. equal ontology
// we use ontology indices here, if the indices are equal, the nodes are from the same ontology
if( o.ontindex != ontindex ) return false;
// 3. equal index
// because the nodes we are comparing are from the same ontology, we can now check for index equality
if( o.index != index ) return false;
return true;
}
/*
public int hashCode() {
return index;
}
*/
public String toString() {
return index+" "+localName;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getIsDefinedByLabel() {
return isDefinedByLabel;
}
public void setIsDefinedByLabel(String isDefinedBy) {
this.isDefinedByLabel = isDefinedBy;
}
public String getSeeAlsoLabel() {
return seeAlsoLabel;
}
public void setSeeAlsoLabel(String seeAlso) {
this.seeAlsoLabel = seeAlso;
}
/**
* Return the domain of a property as an OntResource. As per the Jena specifications, if there are more than one domains, return an arbitrary domain out of them.
* @return OntResource representation of the domain, or null if none exists.
*/
public OntResource getPropertyDomain() {
if( isProp() ) {
try {
if( resource.canAs(ObjectProperty.class) ) {
ObjectProperty p = (ObjectProperty) resource.as(ObjectProperty.class);
OntResource dom = p.getDomain();
return dom;
}
if( resource.canAs(DatatypeProperty.class) ) {
DatatypeProperty p = (DatatypeProperty) resource.as(DatatypeProperty.class);
OntResource dom = p.getDomain();
return dom;
}
if( resource.canAs(AnnotationProperty.class) ) {
AnnotationProperty p = (AnnotationProperty) resource.as(AnnotationProperty.class);
OntResource dom = p.getDomain();
return dom;
}
} catch( Exception e ) {
// cannot find the domain of this property.
//e.printStackTrace();
return null;
}
}
return null;
}
/**
* Return the domain of a property as an OntResource. As per the Jena specifications, if there are more than one domains, return an arbitrary domain out of them.
* @return OntResource representation of the domain, or null if none exists.
*/
public OntResource getPropertyRange() {
if( isProp() ) {
try {
if( resource.canAs(ObjectProperty.class) ) {
ObjectProperty p = (ObjectProperty) resource.as(ObjectProperty.class);
OntResource dom = p.getRange();
return dom;
}
if( resource.canAs(DatatypeProperty.class) ) {
DatatypeProperty p = (DatatypeProperty) resource.as(DatatypeProperty.class);
OntResource dom = p.getRange();
return dom;
}
if( resource.canAs(AnnotationProperty.class) ) {
AnnotationProperty p = (AnnotationProperty) resource.as(AnnotationProperty.class);
OntResource dom = p.getRange();
return dom;
}
} catch( Exception e ) {
// cannot find the domain of this property.
//e.printStackTrace();
return null;
}
}
return null;
}
/**
* Return the properties of a class.
* TODO: This method should throw and exception if called on a property Node.
* @return
*/
public ArrayList<Node> getClassProperties() {
if (isClass()) {
ArrayList<Node> returnList = new ArrayList<Node>();
Ontology currentOntology = Core.getInstance().getOntologyByIndex(
ontindex);
OntClass thisclass = (OntClass) resource.as(OntClass.class);
StmtIterator sIter = thisclass.listProperties();
while (sIter.hasNext()) {
Statement currentStatement = sIter.nextStatement();
//System.out.println("getClassProperties: " + currentStatement+"\n");
Property property = (Property) currentStatement.getPredicate()
.as(Property.class);
if (property.isAnon())
continue; // skip anonymous property values (for now)
if (property.isLiteral())
continue; // skip literal values (since there is no Node
// representation for them)
if (property.canAs(OntResource.class)) { // need OntResource to map to Node.
OntResource c = (OntResource) property.as(OntResource.class);
Node n = null;
try {
n = currentOntology.getNodefromOntResource(c, alignType.aligningClasses);
} catch (Exception e) {
// if this OntResource does not have a Node
// representation, go on to the next one.
//e.printStackTrace();
continue;
}
returnList.add(n);
}
}
return returnList;
}
return null;
}
public ArrayList<String> getpropOrClassNeighbours() {
return propOrClassNeighbours;
}
public ArrayList<String> getIndividuals() {
return individuals;
}
public String getDescriptionsString() {
String result = "";
result+= "URI identifier: (namespace#localname)\n";
result += uri+"\n\n";
result += "Label: (rdfs:label)\n";
result += label+"\n\n";
return result;
}
public String getPropOrClassString() {
String result = "Properties or Classes declared by this concept:\n\n";
if(propOrClassNeighbours.size() == 0) {
result+="The list is empty";
}
for(int i = 0; i < propOrClassNeighbours.size(); i++) {
result+= propOrClassNeighbours.get(i)+"\n";
}
return result;
}
public String getAnnotationsString() {
String result = "";
result+= "Comments: (rdfs:comment)\n";
result += comment+"\n\n";
result += "SeeAlso: (owl:seeAlso)\n";
result += seeAlsoLabel+"\n\n";
result += "IsDefinedBy: (owl:isDefinedBy)\n";
result += isDefinedByLabel+"\n\n";
return result;
}
public String getIndividualsString() {
String result = "List of individuals:\n\n";
if(individuals.size() == 0) {
result+="No instances found for this class";
}
for(int i = 0; i < individuals.size(); i++) {
result+= individuals.get(i)+"\n";
}
return result;
}
/**n is a descendant of this? same as vertex.isNodeDescendant*/
/**
* @param color the color to set
*/
public void setColor(int color) {
this.color = color;
}
/**
* @return the color
*/
public int getColor() {
return color;
}
/**
* @param parent the parent to set
*/
public void addParent(Node parent) {
if( this.parent != null ) this.parent.add(parent);
}
/**
* @return the parent
*/
public ArrayList<Node> getParent() {
return parent;
}
/**
* @param depth the depth to set
*/
public void setDepth(int depth) {
this.depth = depth;
}
/**
* @return the depth
*/
public int getDepth() {
return depth;
}
/**
* method created for the Mappings Candidate Selection in the User Feedback Loop
* @return index + label, if label is meaningful else index + localname
*/
public String getCandidateString() {
String result = index+"";
if(label != null && label.length() > 0){
result+= " "+label;
}
else{
result += " "+localName;
}
return result;
}
/**
* Determine if a certain graphical representation has an object registered with this Node.
* @param c
* @return
*/
public boolean hasGraphicalRepresentation( Class<?> c ) {
Iterator<OntologyConceptGraphics> gr = graphicalRepresentations.iterator();
while( gr.hasNext() ) {
OntologyConceptGraphics g = gr.next();
if ( g.getImplementationClass().equals(c) ) {
return true;
}
}
return false;
}
/**
* Return a graphical representation corresponding to the class that implements it.
* Multiple visualizations can be active in AgreementMaker, each representing
* the same ontologies and concepts.
* @param c The class that implements the visual representation of this node.
* @return
*/
public OntologyConceptGraphics getGraphicalRepresentation( Class<?> c ) {
Iterator<OntologyConceptGraphics> gr = graphicalRepresentations.iterator();
while( gr.hasNext() ) {
OntologyConceptGraphics g = gr.next();
if( g.getImplementationClass().equals(c) ) {
return g;
}
}
return null;
}
/**
* A new graphical representation of this concept has been constructed.
* Add it to the list of graphical representations for this concept.
* @param ocg
*/
public void addGraphicalRepresentation( OntologyConceptGraphics ocg ) { graphicalRepresentations.add(ocg); }
/**
* A graphical representation is no longer displayed, remove it from this concept.
* @param ocg
*/
public void removeGraphicalRepresentation( OntologyConceptGraphics ocg ) {
if( graphicalRepresentations.contains(ocg) )
graphicalRepresentations.remove(ocg);
}
}
|
package com.redhat.ceylon.compiler.typechecker.analyzer;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkAssignable;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkCallable;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkIsExactly;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkSupertype;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkTypeBelongsToContainingScope;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getBaseDeclaration;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypeArguments;
import static com.redhat.ceylon.compiler.typechecker.model.Util.addToIntersection;
import static com.redhat.ceylon.compiler.typechecker.model.Util.addToUnion;
import static com.redhat.ceylon.compiler.typechecker.model.Util.getContainingClassOrInterface;
import static com.redhat.ceylon.compiler.typechecker.model.Util.getOuterClassOrInterface;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isAbstraction;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isTypeUnknown;
import static com.redhat.ceylon.compiler.typechecker.model.Util.producedType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.BottomType;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Generic;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
* Third and final phase of type analysis.
* Finally visit all expressions and determine their types.
* Use type inference to assign types to declarations with
* the local modifier. Finally, assigns types to the
* associated model objects of declarations declared using
* the local modifier.
*
* @author Gavin King
*
*/
public class ExpressionVisitor extends Visitor {
private Tree.Type returnType;
private Tree.Expression switchExpression;
private Declaration returnDeclaration;
private boolean defaultArgument;
private Unit unit;
@Override public void visit(Tree.CompilationUnit that) {
unit = that.getUnit();
super.visit(that);
}
private Declaration beginReturnDeclaration(Declaration d) {
Declaration od = returnDeclaration;
returnDeclaration = d;
return od;
}
private void endReturnDeclaration(Declaration od) {
returnDeclaration = od;
}
private Tree.Type beginReturnScope(Tree.Type t) {
Tree.Type ort = returnType;
returnType = t;
if (returnType instanceof Tree.FunctionModifier ||
returnType instanceof Tree.ValueModifier) {
returnType.setTypeModel( unit.getBottomDeclaration().getType() );
}
return ort;
}
private void endReturnScope(Tree.Type t, TypedDeclaration td) {
if (returnType instanceof Tree.FunctionModifier ||
returnType instanceof Tree.ValueModifier) {
td.setType( returnType.getTypeModel() );
}
returnType = t;
}
@Override public void visit(Tree.DefaultArgument that) {
defaultArgument=true;
super.visit(that);
defaultArgument=false;
}
@Override public void visit(Tree.TypeDeclaration that) {
super.visit(that);
TypeDeclaration td = that.getDeclarationModel();
if (td!=null) {
List<ProducedType> supertypes = td.getType().getSupertypes();
for (int i=0; i<supertypes.size(); i++) {
ProducedType st1 = supertypes.get(i);
for (int j=i+1; j<supertypes.size(); j++) {
ProducedType st2 = supertypes.get(j);
if (st1.getDeclaration().equals(st2.getDeclaration()) /*&& !st1.isExactly(st2)*/) {
if (!st1.isSubtypeOf(st2) && !st2.isSubtypeOf(st1)) {
that.addError("type " + td.getName() +
" has the same supertype twice with incompatible type arguments: " +
st1.getProducedTypeName() + " and " + st2.getProducedTypeName());
}
}
}
if (!isCompletelyVisible(td, st1)) {
that.addError("supertype of type is not visible everywhere type is visible: "
+ st1.getProducedTypeName());
}
}
}
}
@Override public void visit(Tree.TypedDeclaration that) {
super.visit(that);
TypedDeclaration td = that.getDeclarationModel();
if ( td.getType()!=null && !isCompletelyVisible(td,td.getType()) ) {
that.getType().addError("type of declaration is not visible everywhere declaration is visible: "
+ td.getName());
}
}
@Override public void visit(Tree.FunctionArgument that) {
super.visit(that);
ProducedType t = denotableType(that.getExpression().getTypeModel());
that.getDeclarationModel().setType(t);
/*List<ProducedType> list = new ArrayList<ProducedType>();
for (Parameter p: that.getDeclarationModel().getParameterLists().get(0)
.getParameters()) {
list.add(p.getType());
}
ProducedType ft = unit.getCallableDeclaration().getProducedType(null, list);*/
that.getType().setTypeModel(t);
that.setTypeModel(that.getDeclarationModel()
.getProducedTypedReference(null, Collections.<ProducedType>emptyList())
.getFullType());
}
@Override
public void visit(Tree.AnyMethod that) {
super.visit(that);
TypedDeclaration td = that.getDeclarationModel();
for (Tree.ParameterList list: that.getParameterLists()) {
for (Tree.Parameter tp: list.getParameters()) {
if (tp!=null) {
Parameter p = tp.getDeclarationModel();
if (p.getType()!=null && !isCompletelyVisible(td, p.getType())) {
tp.getType().addError("type of parameter is not visible everywhere declaration is visible: "
+ p.getName());
}
}
}
}
}
@Override
public void visit(Tree.AnyClass that) {
super.visit(that);
Class td = that.getDeclarationModel();
if (that.getParameterList()!=null) {
for (Tree.Parameter tp: that.getParameterList().getParameters()) {
if (tp!=null) {
Parameter p = tp.getDeclarationModel();
if (p.getType()!=null && !isCompletelyVisible(td, p.getType())) {
tp.getType().addError("type of parameter is not visible everywhere declaration is visible: "
+ p.getName());
}
}
}
}
}
private boolean isCompletelyVisible(Declaration member, ProducedType pt) {
if (pt.getDeclaration() instanceof UnionType) {
for (ProducedType ct: pt.getDeclaration().getCaseTypes()) {
if ( !isCompletelyVisible(member, ct.substitute(pt.getTypeArguments())) ) {
return false;
}
}
return true;
}
else if (pt.getDeclaration() instanceof IntersectionType) {
for (ProducedType ct: pt.getDeclaration().getSatisfiedTypes()) {
if ( !isCompletelyVisible(member, ct.substitute(pt.getTypeArguments())) ) {
return false;
}
}
return true;
}
else {
if (!isVisible(member, pt.getDeclaration())) {
return false;
}
for (ProducedType at: pt.getTypeArgumentList()) {
if ( at!=null && !isCompletelyVisible(member, at) ) {
return false;
}
}
return true;
}
}
private boolean isVisible(Declaration member, TypeDeclaration type) {
return type instanceof TypeParameter ||
type.isVisible(member.getVisibleScope());
}
@Override public void visit(Tree.Variable that) {
super.visit(that);
if (that.getSpecifierExpression()!=null) {
inferType(that, that.getSpecifierExpression());
if (that.getType()!=null) {
checkType(that.getType().getTypeModel(), that.getSpecifierExpression());
}
}
}
private void initOriginalDeclaration(Tree.Variable that) {
if (that.getType() instanceof Tree.SyntheticVariable) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) that
.getSpecifierExpression().getExpression().getTerm();
((TypedDeclaration) that.getDeclarationModel())
.setOriginalDeclaration((TypedDeclaration) bme.getDeclaration());
}
}
@Override public void visit(Tree.IsCondition that) {
//don't recurse to the Variable, since we don't
//want to check that the specifier expression is
//assignable to the declared variable type
//(nor is it possible to infer the variable type)
that.getType().visit(this);
Tree.Variable v = that.getVariable();
ProducedType type = that.getType().getTypeModel();
if (v!=null) {
//v.getType().visit(this);
Tree.SpecifierExpression se = v.getSpecifierExpression();
ProducedType knownType;
if (se==null) {
knownType = null;
}
else {
se.visit(this);
checkReferenceIsNonVariable(v, se);
/*checkAssignable( se.getExpression().getTypeModel(),
getOptionalType(getObjectDeclaration().getType()),
se.getExpression(),
"expression may not be of void type");*/
initOriginalDeclaration(v);
//this is a bit ugly (the parser sends us a SyntheticVariable
//instead of the real StaticType which it very well knows!)
knownType = se.getExpression().getTypeModel();
if (knownType!=null && knownType.isSubtypeOf(type)) {
that.addError("does not narrow type: " + knownType.getProducedTypeName() +
" is a subtype of " + type.getProducedTypeName());
}
}
defaultTypeToVoid(v);
ProducedType it = knownType==null ? type :
intersectionType(type, knownType, that.getUnit());
if (it.getDeclaration() instanceof BottomType) {
that.addError("tests assignability to Bottom type: intersection of " +
knownType.getProducedTypeName() + " and " +
type.getProducedTypeName() +
" is empty");
}
if (v.getType() instanceof Tree.SyntheticVariable) {
//when we're reusing the original name, we narrow to the
//intersection of the outer type and the type specified
//in the condition
v.getType().setTypeModel(it);
v.getDeclarationModel().setType(it);
}
}
else if (that.getExpression()!=null) {
that.getExpression().visit(this);
}
/*if (that.getExpression()!=null) {
that.getExpression().visit(this);
}*/
checkReified(that, type);
}
private void checkReified(Node that, ProducedType type) {
if (type!=null) {
TypeDeclaration dec = type.getDeclaration();
if (dec instanceof UnionType) {
for (ProducedType pt: dec.getCaseTypes()) {
checkReified(that, pt);
}
}
else if (dec instanceof IntersectionType) {
for (ProducedType pt: dec.getSatisfiedTypes()) {
checkReified(that, pt);
}
}
else if (dec instanceof TypeParameter) {
that.addWarning("type parameter in assignability condition not yet supported (until we implement reified generics)");
}
else if (isGeneric(dec)) {
List<TypeParameter> params = dec.getTypeParameters();
List<ProducedType> args = type.getTypeArgumentList();
if (params.size()==args.size()) {
for (int i=0; i<params.size(); i++) {
TypeParameter tp = params.get(i);
ProducedType ta = args.get(i);
if (ta!=null) {
if (tp.isCovariant()) {
List<ProducedType> list = new ArrayList<ProducedType>();
addToIntersection(list, unit.getVoidDeclaration().getType(), unit);
for (ProducedType st: tp.getSatisfiedTypes()) {
addToIntersection(list, st, unit);
}
IntersectionType ut = new IntersectionType(unit);
ut.setSatisfiedTypes(list);
if (!ta.isExactly(ut.getType())) {
that.addWarning("type argument to covariant type parameter in assignability condition must be " +
ut.getType().getProducedTypeName() + " (until we implement reified generics)");
}
}
else if (tp.isContravariant()) {
if (!(ta.getDeclaration() instanceof BottomType)) {
that.addWarning("type argument to contravariant type parameter in assignability condition must be Bottom (until we implement reified generics)");
}
}
else {
that.addWarning("type argument to invariant type parameter in assignability condition not yet supported (until we implement reified generics)");
}
}
}
}
//else there is another error, so don't bother
//with this check at all
}
}
}
@Override public void visit(Tree.SatisfiesCondition that) {
super.visit(that);
that.addWarning("satisfies conditions not yet supported");
}
@Override public void visit(Tree.ExistsOrNonemptyCondition that) {
//don't recurse to the Variable, since we don't
//want to check that the specifier expression is
//assignable to the declared variable type
//(nor is it possible to infer the variable type)
ProducedType t = null;
Node n = that;
Tree.Term term = null;
Tree.Variable v = that.getVariable();
if (v!=null) {
//v.getType().visit(this);
defaultTypeToVoid(v);
Tree.SpecifierExpression se = v.getSpecifierExpression();
if (se!=null) {
se.visit(this);
if (that instanceof Tree.ExistsCondition) {
inferDefiniteType(v, se);
checkOptionalType(v, se);
}
else if (that instanceof Tree.NonemptyCondition) {
inferNonemptyType(v, se);
checkEmptyOptionalType(v, se);
}
t = se.getExpression().getTypeModel();
n = v;
checkReferenceIsNonVariable(v, se);
initOriginalDeclaration(v);
term = se.getExpression().getTerm();
}
}
else if (that.getExpression()!=null) {
//note: this is only here to handle
// erroneous syntax elegantly
that.getExpression().visit(this);
t = that.getExpression().getTypeModel();
term = that.getExpression().getTerm();
}
/*Tree.Expression e = that.getExpression();
if (e!=null) {
e.visit(this);
t = e.getTypeModel();
n = e;
}*/
if (that instanceof Tree.ExistsCondition) {
checkOptional(t, term, n);
}
else if (that instanceof Tree.NonemptyCondition) {
checkEmpty(t, term, n);
}
}
private void defaultTypeToVoid(Tree.Variable v) {
/*if (v.getType().getTypeModel()==null) {
v.getType().setTypeModel( getVoidDeclaration().getType() );
}*/
v.getType().visit(this);
if (v.getDeclarationModel().getType()==null) {
v.getDeclarationModel().setType( defaultType() );
}
}
private void checkReferenceIsNonVariable(Tree.Variable v,
Tree.SpecifierExpression se) {
if (v.getType() instanceof Tree.SyntheticVariable) {
checkReferenceIsNonVariable((Tree.BaseMemberExpression) se.getExpression().getTerm());
}
}
private void checkReferenceIsNonVariable(Tree.BaseMemberExpression ref) {
Declaration d = ref.getDeclaration();
if (d!=null) {
if (d instanceof Getter) {
ref.addError("referenced value is a getter: " + d.getName());
}
if ( ( (TypedDeclaration) d ).isVariable() ) {
ref.addError("referenced value is variable: " + d.getName());
}
if ( d.isDefault() ) {
ref.addError("referenced value is default and may be refined: " + d.getName());
}
}
}
private void checkEmpty(ProducedType t, Tree.Term term, Node n) {
/*if (t==null) {
n.addError("expression must be a type with fixed size: type not known");
}
else*/ if (t!=null && !unit.isEmptyType(t)) {
term.addError("expression must be a possibly-empty type: " +
t.getProducedTypeName() + " is not possibly-empty");
}
}
private boolean hasUncheckedNulls(Tree.Term term) {
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration d = ((Tree.MemberOrTypeExpression) term).getDeclaration();
return d instanceof TypedDeclaration &&
((TypedDeclaration) d).hasUncheckedNullType();
}
else if (term instanceof Tree.InvocationExpression) {
return hasUncheckedNulls(((Tree.InvocationExpression) term).getPrimary());
}
else {
return false;
}
}
private void checkOptional(ProducedType t, Tree.Term term, Node n) {
/*if (t==null) {
n.addError("expression must be of optional type: type not known");
}
else*/ if (t!=null && !unit.isOptionalType(t) &&
!hasUncheckedNulls(term)) {
term.addError("expression must be of optional type: " +
t.getProducedTypeName() + " is not optional");
}
}
@Override public void visit(Tree.BooleanCondition that) {
super.visit(that);
if (that.getExpression()!=null) {
checkAssignable(that.getExpression().getTypeModel(),
unit.getBooleanDeclaration().getType(), that,
"expression must be of boolean type");
}
}
@Override public void visit(Tree.Resource that) {
super.visit(that);
ProducedType t = null;
Node typedNode = null;
if (that.getExpression()!=null) {
Tree.Expression e = that.getExpression();
t = e.getTypeModel();
typedNode = e;
if (e.getTerm() instanceof Tree.InvocationExpression) {
Tree.InvocationExpression ie = (Tree.InvocationExpression) e.getTerm();
if (!(ie.getPrimary() instanceof Tree.BaseTypeExpression
|| ie.getPrimary() instanceof Tree.QualifiedTypeExpression)) {
e.addError("resource expression is not an unqualified value reference or instantiation");
}
}
else if (!(e.getTerm() instanceof Tree.BaseMemberExpression)){
e.addError("resource expression is not an unqualified value reference or instantiation");
}
}
else if (that.getVariable()!=null) {
t = that.getVariable().getType().getTypeModel();
typedNode = that.getVariable().getType();
Tree.SpecifierExpression se = that.getVariable().getSpecifierExpression();
if (se==null) {
that.getVariable().addError("missing resource specifier");
}
else if (typedNode instanceof Tree.ValueModifier){
typedNode = se.getExpression();
}
}
if (typedNode!=null) {
checkAssignable(t, unit.getCloseableDeclaration().getType(), typedNode,
"resource must be closeable");
}
}
@Override public void visit(Tree.ValueIterator that) {
super.visit(that);
if (that.getVariable()!=null) {
inferContainedType(that.getVariable(), that.getSpecifierExpression());
checkContainedType(that.getVariable(), that.getSpecifierExpression());
}
}
@Override public void visit(Tree.KeyValueIterator that) {
super.visit(that);
if (that.getKeyVariable()!=null && that.getValueVariable()!=null) {
inferKeyType(that.getKeyVariable(), that.getSpecifierExpression());
inferValueType(that.getValueVariable(), that.getSpecifierExpression());
checkKeyValueType(that.getKeyVariable(), that.getValueVariable(),
that.getSpecifierExpression());
}
}
@Override public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
inferType(that, that.getSpecifierOrInitializerExpression());
if (that.getType()!=null) {
checkType(that.getType().getTypeModel(),
that.getSpecifierOrInitializerExpression());
}
}
@Override public void visit(Tree.SpecifierStatement that) {
super.visit(that);
Tree.Term me = that.getBaseMemberExpression();
Tree.SpecifierExpression sie = that.getSpecifierExpression();
if (me instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) me;
Declaration d = bme.getDeclaration();
if (d!=null &&
that.getScope() instanceof Class &&
!d.isDefinedInScope(that.getScope())) {
//then it must be inherited ... TODO: is this totally correct?
//so it's actually a refinement of a formal declaration!
if (d instanceof Value) {
refine((Value) d, bme, that);
}
else if (d instanceof Method) {
refine((Method) d, bme, that);
}
else {
//TODO!
bme.addError("not a reference to a formal attribute: " + d.getName());
}
}
if (d!=null) {
if (d instanceof Value && ((Value) d).isVariable()) {
that.getSpecifierExpression()
.addError("variable values must be assigned using \":=\": " +
d.getName(), 802);
}
else if (d.isToplevel()) {
that.getBaseMemberExpression()
.addError("toplevel declarations may not be specified");
}
}
}
else {
me.addError("illegal specification statement");
}
//TODO: display the value name in the error message
checkType(me.getTypeModel(), sie);
}
private void refine(Value sv, Tree.BaseMemberExpression bme,
Tree.SpecifierStatement that) {
if (sv.isVariable()) {
that.addError("attribute is variable: " + sv.getName());
}
if (!sv.isFormal()) {
bme.addError("attribute is not formal: " + sv.getName());
}
Value v = new Value();
v.setName(sv.getName());
/*if (sie!=null) {
v.setType(sie.getExpression().getTypeModel());
}*/
v.setType(sv.getType());
v.setShared(true);
v.setActual(true);
v.setRefinedDeclaration(v);
v.setUnit(unit);
v.setContainer(that.getScope());
DeclarationVisitor.setVisibleScope(v);
((Class) that.getScope()).getMembers().add(v);
bme.setDeclaration(v);
//bme.setTypeModel(v.getType());
that.setRefinement(true);
}
private void refine(Method sm, Tree.BaseMemberExpression bme,
Tree.SpecifierStatement that) {
if (!sm.isFormal()) {
bme.addError("method is not formal: " + sm.getName());
}
Method m = new Method();
m.setName(sm.getName());
/*if (sie!=null) {
v.setType(sie.getExpression().getTypeModel());
}*/
m.setType(sm.getType());
m.getParameterLists().addAll(sm.getParameterLists()); //TODO:broken!
m.getTypeParameters().addAll(sm.getTypeParameters()); //TODO:broken!
m.setShared(true);
m.setActual(true);
m.setRefinedDeclaration(m);
m.setUnit(unit);
m.setContainer(that.getScope());
DeclarationVisitor.setVisibleScope(m);
((Class) that.getScope()).getMembers().add(m);
bme.setDeclaration(m);
//bme.setTypeModel(v.getType());
that.setRefinement(true);
}
@Override public void visit(Tree.Parameter that) {
super.visit(that);
Tree.SpecifierExpression se = that.getDefaultArgument()==null ?
null :
that.getDefaultArgument().getSpecifierExpression();
ProducedType t = that.getDeclarationModel().getProducedTypedReference(null,
Collections.<ProducedType>emptyList()).getFullType();
checkType(t, se);
}
@Override
public void visit(Tree.ValueParameterDeclaration that) {
if (that.getType() instanceof Tree.LocalModifier) {
ValueParameter d = that.getDeclarationModel();
if (d!=null) {
that.getType().setTypeModel(d.getType());
}
}
super.visit(that);
}
private void checkType(ProducedType declaredType,
Tree.SpecifierOrInitializerExpression sie) {
if (sie!=null && sie.getExpression()!=null) {
checkAssignable(sie.getExpression().getTypeModel(), declaredType, sie,
"specified expression must be assignable to declared type");
}
}
private void checkFunctionType(ProducedType et, Tree.Type that) {
if (et!=null) {
checkAssignable(et, that.getTypeModel(), that,
"specified reference return type must be assignable to declared return type");
}
}
private void checkOptionalType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
if (se!=null && se.getExpression()!=null) {
ProducedType set = se.getExpression().getTypeModel();
if (set!=null) {
checkAssignable(unit.getDefiniteType(set), vt, se,
"specified expression must be assignable to declared type");
}
}
}
}
private void checkEmptyOptionalType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
checkType(unit.getOptionalType(unit.getPossiblyNoneType(vt)), se);
}
}
private void checkContainedType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
checkType(unit.getIterableType(vt), se);
}
}
private void checkKeyValueType(Tree.Variable key, Tree.Variable value,
Tree.SpecifierExpression se) {
if (key.getType()!=null && value.getType()!=null) {
ProducedType kt = key.getType().getTypeModel();
ProducedType vt = value.getType().getTypeModel();
checkType(unit.getIterableType(unit.getEntryType(kt, vt)), se);
}
}
@Override public void visit(Tree.AttributeGetterDefinition that) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnScope(rt, that.getDeclarationModel());
endReturnDeclaration(od);
Setter setter = that.getDeclarationModel().getSetter();
if (setter!=null) {
setter.getParameter().setType(that.getDeclarationModel().getType());
}
}
@Override public void visit(Tree.AttributeArgument that) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
@Override public void visit(Tree.AttributeSetterDefinition that) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
@Override public void visit(Tree.MethodDeclaration that) {
super.visit(that);
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType et = e.getTypeModel();
for (Tree.ParameterList pl: that.getParameterLists()) {
if (checkCallable(et, se, "specified value must be a reference to a function or class")){
/*if (e.getTerm() instanceof MemberOrTypeExpression) {
Declaration d = ((MemberOrTypeExpression) e.getTerm()).getDeclaration();
if (d instanceof Class && ((Class) d).isAbstract()) {
se.addError("specified reference is to an abstract class: " + d.getName());
}
}*/
if (pl.getParameters().size()+1==et.getTypeArgumentList().size()) {
int i=0;
for (Tree.Parameter p: pl.getParameters()) {
if (p!=null) {
i++;
ProducedType rt = et.getTypeArgumentList().get(i);
ProducedType pt = p.getDeclarationModel().getProducedTypedReference(null,
Collections.<ProducedType>emptyList()).getFullType();
checkIsExactly(rt, pt, p.getType(),
"specified reference parameter type must be exactly the same as declared type of parameter " +
p.getDeclarationModel().getName());
}
}
}
else {
se.addError("specified reference must have the same number of parameters");
}
et = et.getTypeArgumentList().get(0);
}
else {
return; //Note: early exit!
}
}
inferFunctionType(that, et);
if (that.getType()!=null) {
checkFunctionType(et, that.getType());
}
}
}
}
@Override public void visit(Tree.MethodDefinition that) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
@Override public void visit(Tree.MethodArgument that) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
@Override public void visit(Tree.ClassDefinition that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
Class c = that.getDeclarationModel();
if (!c.isAbstract()) {
validateEnumeratedSupertypes(that, c);
}
}
@Override public void visit(Tree.ClassOrInterface that) {
super.visit(that);
validateEnumeratedSupertypeArguments(that, that.getDeclarationModel());
}
@Override public void visit(Tree.InterfaceDefinition that) {
Tree.Type rt = beginReturnScope(null);
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
}
@Override public void visit(Tree.ObjectDefinition that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getAnonymousClass());
}
@Override public void visit(Tree.ObjectArgument that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getAnonymousClass());
}
@Override public void visit(Tree.ClassDeclaration that) {
super.visit(that);
Class alias = that.getDeclarationModel();
Class c = alias.getExtendedTypeDeclaration();
if (c!=null) {
//that.getTypeSpecifier().getType().get
ProducedType at = alias.getExtendedType();
int cps = c.getParameterList().getParameters().size();
int aps = alias.getParameterList().getParameters().size();
if (cps!=aps) {
that.addError("wrong number of initializer parameters declared by class alias: " +
alias.getName());
}
for (int i=0; i<(cps<=aps ? cps : aps); i++) {
Parameter ap = alias.getParameterList().getParameters().get(i);
Parameter cp = c.getParameterList().getParameters().get(i);
ProducedType pt = at.getTypedParameter(cp).getType();
ap.setAliasedParameter(cp);
//TODO: properly check type of functional parameters!!
checkAssignable(ap.getType(), pt, that, "alias parameter " +
ap.getName() + " must be assignable to corresponding class parameter " +
cp.getName());
}
}
}
private ProducedType denotableType(ProducedType pt) {
if ( pt.getDeclaration().isAnonymous() ) {
List<ProducedType> list = new ArrayList<ProducedType>();
addToIntersection(list, pt.getSupertype(pt.getDeclaration().getExtendedTypeDeclaration()), unit);
for (TypeDeclaration td: pt.getDeclaration().getSatisfiedTypeDeclarations()) {
addToIntersection(list, pt.getSupertype(td), unit);
}
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(list);
return it.getType();
}
else {
return pt;
}
}
private void inferType(Tree.TypedDeclaration that,
Tree.SpecifierOrInitializerExpression spec) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (spec!=null) {
setType(local, spec, that);
}
else {
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
}
}
private void inferFunctionType(Tree.TypedDeclaration that, ProducedType et) {
if (that.getType() instanceof Tree.FunctionModifier) {
Tree.FunctionModifier local = (Tree.FunctionModifier) that.getType();
if (et!=null) {
setFunctionType(local, et, that);
}
}
}
private void inferDefiniteType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromOptionalType(local, se, that);
}
else {
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
}
}
private void inferNonemptyType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromEmptyType(local, se, that);
}
else {
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
}
}
private void inferContainedType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromIterableType(local, se, that);
}
else {
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
}
}
private void inferKeyType(Tree.Variable key,
Tree.SpecifierExpression se) {
if (key.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) key.getType();
if (se!=null) {
setTypeFromKeyType(local, se, key);
}
else {
// local.addError("could not infer type of key: " +
// name(key.getIdentifier()));
}
}
}
private void inferValueType(Tree.Variable value,
Tree.SpecifierExpression se) {
if (value.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) value.getType();
if (se!=null) {
setTypeFromValueType(local, se, value);
}
else {
// local.addError("could not infer type of value: " +
// name(value.getIdentifier()));
}
}
}
private void setTypeFromOptionalType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
ProducedType t;
if (unit.isOptionalType(expressionType)) {
t = unit.getDefiniteType(expressionType);
}
else {
t=expressionType;
}
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
private void setTypeFromEmptyType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
ProducedType t;
if (unit.isEmptyType(expressionType)) {
t = unit.getNonemptyDefiniteType(expressionType);
}
else {
t = expressionType;
}
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
private void setTypeFromIterableType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
if (se.getExpression()!=null) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
if (unit.isIterableType(expressionType)) {
ProducedType t = unit.getIteratedType(expressionType);
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
return;
}
}
}
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
private void setTypeFromKeyType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
if (se.getExpression()!=null) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
if (unit.isIterableType(expressionType)) {
ProducedType entryType = unit.getIteratedType(expressionType);
if (entryType!=null) {
if (unit.isEntryType(entryType)) {
ProducedType et = unit.getKeyType(entryType);
local.setTypeModel(et);
that.getDeclarationModel().setType(et);
return;
}
}
}
}
}
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
private void setTypeFromValueType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
if (se.getExpression()!=null) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
if (unit.isIterableType(expressionType)) {
ProducedType entryType = unit.getIteratedType(expressionType);
if (entryType!=null) {
if (unit.isEntryType(entryType)) {
ProducedType et = unit.getValueType(entryType);
local.setTypeModel(et);
that.getDeclarationModel().setType(et);
return;
}
}
}
}
}
// local.addError("could not infer type of: " +
// name(that.getIdentifier()));
}
private void setType(Tree.LocalModifier local,
Tree.SpecifierOrInitializerExpression s,
Tree.TypedDeclaration that) {
if (s.getExpression()!=null) {
ProducedType t = denotableType(s.getExpression().getTypeModel());
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
private void setFunctionType(Tree.FunctionModifier local,
ProducedType et, Tree.TypedDeclaration that) {
ProducedType t = denotableType(et);
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
@Override public void visit(Tree.Throw that) {
super.visit(that);
if (that.getExpression()!=null) {
checkAssignable(that.getExpression().getTypeModel(),
unit.getExceptionDeclaration().getType(),
that.getExpression(),
"thrown expression must be an exception");
}
}
@Override public void visit(Tree.Return that) {
super.visit(that);
if (returnType==null) {
//misplaced return statements are already handled by ControlFlowVisitor
//missing return types declarations already handled by TypeVisitor
//that.addError("could not determine expected return type");
}
else {
that.setDeclaration(returnDeclaration);
Tree.Expression e = that.getExpression();
if (e==null) {
if (!(returnType instanceof Tree.VoidModifier)) {
that.addError("a non-void method or getter must return a value: " +
returnDeclaration.getName());
}
}
else {
ProducedType et = returnType.getTypeModel();
ProducedType at = e.getTypeModel();
if (returnType instanceof Tree.VoidModifier) {
that.addError("a void method, setter, or class initializer may not return a value: " +
returnDeclaration.getName());
}
else if (returnType instanceof Tree.LocalModifier) {
inferReturnType(et, at);
}
else {
checkAssignable(at, et, that.getExpression(),
"returned expression must be assignable to return type of " +
returnDeclaration.getName());
}
}
}
}
private void inferReturnType(ProducedType et, ProducedType at) {
if (at!=null) {
at = denotableType(at);
if (et==null || et.isSubtypeOf(at)) {
returnType.setTypeModel(at);
}
else {
if (!at.isSubtypeOf(et)) {
UnionType ut = new UnionType(unit);
List<ProducedType> list = new ArrayList<ProducedType>();
addToUnion(list, et);
addToUnion(list, at);
ut.setCaseTypes(list);
returnType.setTypeModel( ut.getType() );
}
}
}
}
/*@Override public void visit(Tree.OuterExpression that) {
that.getPrimary().visit(this);
ProducedType pt = that.getPrimary().getTypeModel();
if (pt!=null) {
if (pt.getDeclaration() instanceof ClassOrInterface) {
that.setTypeModel(getOuterType(that, (ClassOrInterface) pt.getDeclaration()));
//TODO: some kind of MemberReference
}
else {
that.addError("can't use outer on a type parameter");
}
}
}*/
ProducedType unwrap(ProducedType pt, Tree.QualifiedMemberOrTypeExpression mte) {
ProducedType result;
Tree.MemberOperator op = mte.getMemberOperator();
if (op instanceof Tree.SafeMemberOp) {
if (unit.isOptionalType(pt)) {
result = unit.getDefiniteType(pt);
}
else {
mte.getPrimary().addError("receiver not of optional type");
result = pt;
}
}
else if (op instanceof Tree.SpreadOp) {
ProducedType st = unit.getNonemptySequenceType(pt);
if (st==null) {
mte.getPrimary().addError("receiver not of type: Sequence");
result = pt;
}
else {
result = unit.getElementType(pt);
}
}
else {
result = pt;
}
if (result==null) {
result = new UnknownType(mte.getUnit()).getType();
}
return result;
}
ProducedType wrap(ProducedType pt, ProducedType receivingType,
Tree.QualifiedMemberOrTypeExpression mte) {
Tree.MemberOperator op = mte.getMemberOperator();
if (op instanceof Tree.SafeMemberOp) {
return unit.getOptionalType(pt);
}
else if (op instanceof Tree.SpreadOp) {
ProducedType st = unit.getSequenceType(pt);
return unit.isEmptyType(receivingType) ?
unit.getEmptyType(st) : st;
}
else {
return pt;
}
}
@Override public void visit(Tree.InvocationExpression that) {
boolean isDirectInvocation = that.getPrimary() instanceof Tree.MemberOrTypeExpression;
if (isDirectInvocation) {
((Tree.MemberOrTypeExpression) that.getPrimary()).setDirectlyInvoked(true);
}
if (that.getPositionalArgumentList()!=null) {
that.getPositionalArgumentList().visit(this);
if (isDirectInvocation) {
//set up the "signature" on the primary
//so that we can resolve the the right
//overloaded declaration
List<ProducedType> sig = new ArrayList<ProducedType>();
for (Tree.PositionalArgument pa: that.getPositionalArgumentList()
.getPositionalArguments()) {
sig.add(pa.getExpression().getTypeModel());
}
((Tree.MemberOrTypeExpression) that.getPrimary()).setSignature(sig);
}
}
if (that.getNamedArgumentList()!=null) {
that.getNamedArgumentList().visit(this);
}
that.getPrimary().visit(this);
visitInvocation(that);
}
private void visitInvocation(Tree.InvocationExpression that) {
Tree.Primary pr = that.getPrimary();
if (pr==null) {
that.addError("malformed invocation expression");
}
else if (pr instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression mte = (Tree.StaticMemberOrTypeExpression) pr;
Declaration dec = mte.getDeclaration();
if ( mte.getTarget()==null && dec instanceof Functional &&
mte.getTypeArguments() instanceof Tree.InferredTypeArguments ) {
List<ProducedType> typeArgs = getInferedTypeArguments(that, (Functional) dec);
mte.getTypeArguments().setTypeModels(typeArgs);
if (pr instanceof Tree.BaseTypeExpression) {
visitBaseTypeExpression((Tree.BaseTypeExpression) pr,
(TypeDeclaration) dec, typeArgs, mte.getTypeArguments());
}
else if (pr instanceof Tree.QualifiedTypeExpression) {
visitQualifiedTypeExpression((Tree.QualifiedTypeExpression) pr,
((Tree.QualifiedTypeExpression) pr).getPrimary().getTypeModel(),
(TypeDeclaration) dec, typeArgs, mte.getTypeArguments());
}
else if (pr instanceof Tree.BaseMemberExpression) {
visitBaseMemberExpression((Tree.BaseMemberExpression) pr,
(TypedDeclaration) dec, typeArgs, mte.getTypeArguments());
}
else if (pr instanceof Tree.QualifiedMemberExpression) {
visitQualifiedMemberExpression((Tree.QualifiedMemberExpression) pr,
(TypedDeclaration) dec, typeArgs, mte.getTypeArguments());
}
}
visitInvocation(that, mte.getTarget());
}
else if (pr instanceof Tree.ExtendedTypeExpression) {
visitInvocation(that, ((Tree.ExtendedTypeExpression) pr).getTarget());
}
else {
visitInvocation(that, null);
}
}
private List<ProducedType> getInferedTypeArguments(Tree.InvocationExpression that,
Functional dec) {
List<ProducedType> typeArgs = new ArrayList<ProducedType>();
if (!dec.getParameterLists().isEmpty()) {
ParameterList parameters = dec.getParameterLists().get(0);
for (TypeParameter tp: dec.getTypeParameters()) {
if (!tp.isSequenced()) {
typeArgs.add(constrainInferredType(dec, tp,
inferTypeArgument(that, tp, parameters)));
}
}
}
return typeArgs;
}
private ProducedType constrainInferredType(Functional dec,
TypeParameter tp, ProducedType ta) {
List<ProducedType> list = new ArrayList<ProducedType>();
addToIntersection(list, ta, unit);
//Intersect the inferred type with any
//upper bound constraints on the type. This
//helps with cases like passing an arg of
//type String? to a parameter of type T?
for (ProducedType st: tp.getSatisfiedTypes()) {
//TODO: st.getProducedType(receiver, dec, typeArgs);
if (//if the upper bound is a type parameter, ignore it
!dec.getTypeParameters().contains(st.getDeclaration()) &&
(st.getQualifyingType()==null ||
!dec.getTypeParameters().contains(st.getQualifyingType().getDeclaration())) &&
//TODO: remove this awful hack that
//tries to work around the possibility
//that a type parameter appears in the
//upper bound!
!st.getDeclaration().isParameterized() &&
(st.getQualifyingType()==null ||
!st.getQualifyingType().getDeclaration().isParameterized())) {
addToIntersection(list, st, unit);
}
}
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(list);
ProducedType type = it.canonicalize().getType();
return type;
}
private ProducedType inferTypeArgument(Tree.InvocationExpression that,
TypeParameter tp, ParameterList parameters) {
List<ProducedType> inferredTypes = new ArrayList<ProducedType>();
if (that.getPositionalArgumentList()!=null) {
inferTypeArgument(tp, parameters, that.getPositionalArgumentList(), inferredTypes);
}
else if (that.getNamedArgumentList()!=null) {
inferTypeArgument(tp, parameters, that.getNamedArgumentList(), inferredTypes);
}
UnionType ut = new UnionType(unit);
ut.setCaseTypes(inferredTypes);
return ut.getType();
}
private void inferTypeArgument(TypeParameter tp, ParameterList parameters,
Tree.NamedArgumentList args, List<ProducedType> inferredTypes) {
for (Tree.NamedArgument arg: args.getNamedArguments()) {
ProducedType type = null;
if (arg instanceof Tree.SpecifiedArgument) {
type = ((Tree.SpecifiedArgument) arg).getSpecifierExpression()
.getExpression().getTypeModel();
}
else if (arg instanceof Tree.TypedArgument) {
//TODO: broken for method args
type = ((Tree.TypedArgument) arg).getType().getTypeModel();
}
if (type!=null) {
Parameter parameter = getMatchingParameter(parameters, arg);
if (parameter!=null) {
addToUnion(inferredTypes, inferTypeArg(tp, parameter.getType(),
type, new ArrayList<TypeParameter>()));
}
}
}
Tree.SequencedArgument sa = args.getSequencedArgument();
if (sa!=null) {
Parameter sp = getSequencedParameter(parameters);
if (sp!=null) {
ProducedType spt = unit.getElementType(sp.getType());
for (Tree.Expression e: args.getSequencedArgument()
.getExpressionList().getExpressions()) {
ProducedType sat = e.getTypeModel();
if (sat!=null) {
addToUnion(inferredTypes, inferTypeArg(tp, spt, sat,
new ArrayList<TypeParameter>()));
}
}
}
}
}
private void inferTypeArgument(TypeParameter tp, ParameterList parameters,
Tree.PositionalArgumentList args, List<ProducedType> inferredTypes) {
for (int i=0; i<parameters.getParameters().size(); i++) {
Parameter parameter = parameters.getParameters().get(i);
if (args.getPositionalArguments().size()>i) {
if (parameter.isSequenced() && args.getEllipsis()==null) {
ProducedType spt = unit.getElementType(parameter.getType());
for (int k=i; k<args.getPositionalArguments().size(); k++) {
ProducedType sat = args.getPositionalArguments().get(k)
.getExpression().getTypeModel();
if (sat!=null) {
addToUnion(inferredTypes, inferTypeArg(tp, spt, sat,
new ArrayList<TypeParameter>()));
}
}
break;
}
else {
Tree.PositionalArgument a = args.getPositionalArguments().get(i);
if (a.getExpression()!=null) {
ProducedType pt;
if (parameter instanceof FunctionalParameter) {
//TODO: this is very incomplete!
List<ProducedType> list = new ArrayList<ProducedType>();
list.add(parameter.getType());
for (Parameter p: ((FunctionalParameter) parameter).getParameterLists().get(0)
.getParameters()) {
list.add(p.getType());
}
pt = unit.getCallableDeclaration().getProducedType(null, list);
}
else {
pt = parameter.getType();
}
addToUnion(inferredTypes, inferTypeArg(tp, pt,
getPositionalArgumentType(a),
new ArrayList<TypeParameter>()));
}
}
}
}
}
private ProducedType union(List<ProducedType> types) {
if (types.isEmpty()) {
return null;
}
UnionType ut = new UnionType(unit);
ut.setCaseTypes(types);
return ut.getType();
}
private ProducedType intersection(List<ProducedType> types) {
if (types.isEmpty()) {
return null;
}
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(types);
return it.canonicalize().getType();
}
private ProducedType inferTypeArg(TypeParameter tp, ProducedType paramType,
ProducedType argType, List<TypeParameter> visited) {
if (paramType!=null) {
if (paramType.getDeclaration() instanceof TypeParameter &&
paramType.getDeclaration().equals(tp)) {
return denotableType(argType);
}
else if (paramType.getDeclaration() instanceof UnionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: paramType.getDeclaration().getCaseTypes()) {
addToIntersection(list, inferTypeArg(tp,
ct.substitute(paramType.getTypeArguments()),
argType, visited), unit);
}
return intersection(list);
}
else if (paramType.getDeclaration() instanceof IntersectionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: paramType.getDeclaration().getSatisfiedTypes()) {
addToUnion(list, inferTypeArg(tp,
ct.substitute(paramType.getTypeArguments()),
argType, visited));
}
return union(list);
}
else if (argType.getDeclaration() instanceof UnionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: argType.getDeclaration().getCaseTypes()) {
addToUnion(list, inferTypeArg(tp, paramType,
ct.substitute(paramType.getTypeArguments()),
visited));
}
return union(list);
}
else if (argType.getDeclaration() instanceof IntersectionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: argType.getDeclaration().getSatisfiedTypes()) {
addToIntersection(list, inferTypeArg(tp, paramType,
ct.substitute(paramType.getTypeArguments()),
visited), unit);
}
return intersection(list);
}
else if (paramType.getDeclaration() instanceof TypeParameter) {
TypeParameter tp2 = (TypeParameter) paramType.getDeclaration();
if (!visited.contains(tp2)) {
visited.add(tp2);
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType pt: tp2.getSatisfiedTypes()) {
addToUnion(list, inferTypeArg(tp, pt, argType, visited) );
ProducedType st = argType.getSupertype(pt.getDeclaration());
if (st!=null) {
for (int j=0; j<pt.getTypeArgumentList().size(); j++) {
if (st.getTypeArgumentList().size()>j) {
addToUnion(list, inferTypeArg(tp,
pt.getTypeArgumentList().get(j),
st.getTypeArgumentList().get(j),
visited));
}
}
}
}
return union(list);
}
else {
return null;
}
}
else {
ProducedType st = argType.getSupertype(paramType.getDeclaration());
if (st!=null) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (int j=0; j<paramType.getTypeArgumentList().size(); j++) {
if (st.getTypeArgumentList().size()>j) {
addToUnion(list, inferTypeArg(tp,
paramType.getTypeArgumentList().get(j),
st.getTypeArgumentList().get(j),
visited));
}
}
return union(list);
}
else {
return null;
}
}
}
else {
return null;
}
}
/*@Override public void visit(Tree.ExtendedType that) {
super.visit(that);
Tree.Primary pr = that.getTypeExpression();
Tree.PositionalArgumentList pal = that.getPositionalArgumentList();
if (pr==null || pal==null) {
that.addError("malformed expression");
}
else {
visitInvocation(pal, null, that, pr);
}
}*/
private void visitInvocation(Tree.InvocationExpression that, ProducedReference prf) {
if (prf==null || !prf.isFunctional()) {
ProducedType pt = that.getPrimary().getTypeModel();
if (pt!=null) {
if (checkCallable(pt, that.getPrimary(),
"invoked expression must be callable")) {
List<ProducedType> typeArgs = pt.getTypeArgumentList();
if (!typeArgs.isEmpty()) {
that.setTypeModel(typeArgs.get(0));
}
//typecheck arguments using the type args of Callable
checkIndirectInvocationArguments(that, typeArgs);
}
}
}
else {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
Functional dec = (Functional) mte.getDeclaration();
if (!(that.getPrimary() instanceof Tree.ExtendedTypeExpression)) {
if (dec instanceof Class && ((Class) dec).isAbstract()) {
that.addError("abstract classes may not be instantiated");
}
}
if (that.getNamedArgumentList()!=null &&
dec.isAbstraction()) {
//TODO: this is not really right - it's the fact
// that we're calling Java and don't have
// meaningful parameter names that is the
// real problem, not the overload
that.addError("overloaded declarations may not be called using named arguments: " +
dec.getName());
}
//that.setTypeModel(prf.getType());
ProducedType ct = that.getPrimary().getTypeModel();
if (ct!=null && !ct.getTypeArgumentList().isEmpty()) {
//pull the return type out of the Callable
that.setTypeModel(ct.getTypeArgumentList().get(0));
}
if (that.getNamedArgumentList() != null) {
List<ParameterList> parameterLists = dec.getParameterLists();
if(!parameterLists.isEmpty()
&& !parameterLists.get(0).isNamedParametersSupported()) {
that.addError("named invocations of Java methods not supported");
}
}
if (dec.isAbstraction()) {
//nothing to check the argument types against
//that.addError("no matching overloaded declaration");
}
else {
//typecheck arguments using the parameter list
//of the target declaration
checkInvocationArguments(that, prf, dec);
}
}
}
private void checkIndirectInvocationArguments(
Tree.InvocationExpression that, List<ProducedType> typeArgs) {
if (that.getNamedArgumentList() != null) {
that.addError("named arguments not supported for indirect invocations");
}
if (that.getPositionalArgumentList() != null) {
if (that.getPositionalArgumentList().getEllipsis()!=null) {
that.addError("sequenced arguments not supported for indirect invocations");
}
List<Tree.PositionalArgument> args = that.getPositionalArgumentList()
.getPositionalArguments();
int argCount = args.size();
int paramCount = typeArgs.size()-1;
if (argCount<paramCount) {
that.addError("not enough arguments: " +
paramCount + " arguments required");
}
if (argCount>paramCount) {
that.addError("too many arguments: " +
paramCount + " arguments required");
}
for (int i=0; i<paramCount && i<argCount; i++) {
Tree.PositionalArgument arg = args.get(i);
checkAssignable(getPositionalArgumentType(arg),
typeArgs.get(i+1), arg,
"argument must be assignable to parameter type");
}
}
}
private void checkInvocationArguments(Tree.InvocationExpression that,
ProducedReference prf, Functional dec) {
List<ParameterList> pls = dec.getParameterLists();
if (pls.isEmpty()) {
if (dec instanceof TypeDeclaration) {
that.addError("type cannot be instantiated: " +
dec.getName() + " (or return statement is missing)");
}
else {
that.addError("member cannot be invoked: " +
dec.getName());
}
}
else /*if (!dec.isOverloaded())*/ {
ParameterList pl = pls.get(0);
if ( that.getPositionalArgumentList()!=null ) {
checkPositionalArguments(pl, prf, that.getPositionalArgumentList());
}
if ( that.getNamedArgumentList()!=null ) {
if(pl.isNamedParametersSupported()) {
that.getNamedArgumentList().getNamedArgumentList().setParameterList(pl);
checkNamedArguments(pl, prf, that.getNamedArgumentList());
}
}
}
}
private void checkNamedArguments(ParameterList pl, ProducedReference pr,
Tree.NamedArgumentList nal) {
List<Tree.NamedArgument> na = nal.getNamedArguments();
Set<Parameter> foundParameters = new HashSet<Parameter>();
for (Tree.NamedArgument a: na) {
Parameter p = getMatchingParameter(pl, a);
if (p==null) {
a.addError("no matching parameter for named argument " +
name(a.getIdentifier()) + " declared by " +
pr.getDeclaration().getName(), 101);
}
else {
if (!foundParameters.add(p)) {
a.addError("duplicate argument for parameter: " +
p.getName());
}
checkNamedArgument(a, pr, p);
}
}
Tree.SequencedArgument sa = nal.getSequencedArgument();
if (sa!=null) {
Parameter sp = getSequencedParameter(pl);
if (sp==null) {
sa.addError("no matching sequenced parameter declared by "
+ pr.getDeclaration().getName());
}
else {
if (!foundParameters.add(sp)) {
sa.addError("duplicate argument for parameter: " +
sp.getName());
}
checkSequencedArgument(sa, pr, sp);
}
}
for (Parameter p: pl.getParameters()) {
if (!foundParameters.contains(p) &&
!p.isDefaulted() && !p.isSequenced()) {
nal.addError("missing named argument to parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
}
}
private void checkNamedArgument(Tree.NamedArgument a, ProducedReference pr,
Parameter p) {
a.setParameter(p);
ProducedType argType = null;
if (a instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) a;
Expression e = sa.getSpecifierExpression().getExpression();
if (e!=null) {
argType = e.getTypeModel();
}
}
else if (a instanceof Tree.TypedArgument) {
Tree.TypedArgument ta = (Tree.TypedArgument) a;
argType = ta.getDeclarationModel().getProducedTypedReference(null,
//assuming an argument can't have type params
Collections.<ProducedType>emptyList()).getFullType();
//argType = ta.getType().getTypeModel();
}
checkAssignable(argType, pr.getTypedParameter(p.getAliasedParameter()).getFullType(),
a, "named argument must be assignable to parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
private void checkSequencedArgument(Tree.SequencedArgument a, ProducedReference pr,
Parameter p) {
a.setParameter(p);
for (Tree.Expression e: a.getExpressionList().getExpressions()) {
ProducedType paramType = pr.getTypedParameter(p.getAliasedParameter())
.getFullType();
if (paramType==null) {
paramType = new UnknownType(a.getUnit()).getType();
}
checkAssignable(e.getTypeModel(), unit.getElementType(paramType), a,
"sequenced argument must be assignable to sequenced parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
}
private Parameter getMatchingParameter(ParameterList pl, Tree.NamedArgument na) {
String name = name(na.getIdentifier());
for (Parameter p: pl.getParameters()) {
if (p.getName().equals(name)) {
return p;
}
}
return null;
}
private Parameter getSequencedParameter(ParameterList pl) {
int s = pl.getParameters().size();
if (s==0) return null;
Parameter p = pl.getParameters().get(s-1);
if (p.isSequenced()) {
return p;
}
else {
return null;
}
}
private void checkPositionalArguments(ParameterList pl, ProducedReference pr,
Tree.PositionalArgumentList pal) {
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
List<Parameter> params = pl.getParameters();
for (int i=0; i<params.size(); i++) {
Parameter p = params.get(i);
if (i>=args.size()) {
if (!p.isDefaulted() && !p.isSequenced()) {
pal.addError("missing argument to parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
if (p.isSequenced() && pal.getEllipsis()!=null) {
pal.addError("missing argument to sequenced parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
}
else {
ProducedType paramType = pr.getTypedParameter(p.getAliasedParameter())
.getFullType();
if (p.isSequenced() && pal.getEllipsis()==null) {
checkSequencedPositionalArgument(p, pr, pal, i, paramType);
return;
}
else {
checkPositionalArgument(p, pr, args.get(i), paramType);
}
}
}
for (int i=params.size(); i<args.size(); i++) {
args.get(i).addError("no matching parameter for argument declared by " +
pr.getDeclaration().getName());
}
if (pal.getEllipsis()!=null &&
(params.isEmpty() || !params.get(params.size()-1).isSequenced())) {
pal.getEllipsis().addError("no matching sequenced parameter declared by " +
pr.getDeclaration().getName());
}
}
private void checkSequencedPositionalArgument(Parameter p, ProducedReference pr,
Tree.PositionalArgumentList pal, int i, ProducedType paramType) {
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
ProducedType at = paramType==null ? null :
unit.getElementType(paramType);
for (int j=i; j<args.size(); j++) {
Tree.PositionalArgument a = args.get(j);
a.setParameter(p);
Tree.Expression e = a.getExpression();
if (e==null) {
//TODO: this case is temporary until we get support for SPECIAL_ARGUMENTs
}
else {
/*if (pal.getEllipsis()!=null) {
if (i<args.size()-1) {
a.addError("too many arguments to sequenced parameter: " +
p.getName());
}
if (!paramType.isSupertypeOf(argType)) {
a.addError("argument not assignable to parameter type: " +
p.getName() + " since " +
argType.getProducedTypeName() + " is not " +
paramType.getProducedTypeName());
}
}
else {*/
checkAssignable(e.getTypeModel(), at, a,
"argument must be assignable to sequenced parameter " +
p.getName()+ " of " + pr.getDeclaration().getName());
}
}
}
private void checkPositionalArgument(Parameter p, ProducedReference pr,
Tree.PositionalArgument a, ProducedType paramType) {
a.setParameter(p);
if (a.getExpression()==null) {
//TODO: this case is temporary until we get support for SPECIAL_ARGUMENTs
}
else {
checkAssignable(getPositionalArgumentType(a), paramType, a,
"argument must be assignable to parameter " +
p.getName() + " of " + pr.getDeclaration().getName());
}
}
private ProducedType getPositionalArgumentType(Tree.PositionalArgument a) {
Tree.Expression e = a.getExpression();
return e==null ? null : e.getTypeModel();
}
@Override public void visit(Tree.Annotation that) {
super.visit(that);
Declaration dec = ((Tree.MemberOrTypeExpression) that.getPrimary()).getDeclaration();
if (dec!=null && !dec.isToplevel()) {
that.getPrimary().addError("annotation must be a toplevel method reference");
}
}
@Override public void visit(Tree.IndexExpression that) {
super.visit(that);
ProducedType pt = type(that);
if (pt==null) {
that.addError("could not determine type of receiver");
}
else {
if (that.getIndexOperator() instanceof Tree.SafeIndexOp) {
if (unit.isOptionalType(pt)) {
pt = unit.getDefiniteType(pt);
}
else {
that.getPrimary().addError("receiving type not of optional type: " +
pt.getDeclaration().getName() + " is not a subtype of Optional");
}
}
if (that.getElementOrRange()==null) {
that.addError("malformed index expression");
}
else {
if (that.getElementOrRange() instanceof Tree.Element) {
ProducedType cst = pt.getSupertype(unit.getCorrespondenceDeclaration());
if (cst==null) {
that.getPrimary().addError("illegal receiving type for index expression: " +
pt.getDeclaration().getName() + " is not a subtype of Correspondence");
}
else {
List<ProducedType> args = cst.getTypeArgumentList();
ProducedType kt = args.get(0);
ProducedType vt = args.get(1);
Tree.Element e = (Tree.Element) that.getElementOrRange();
checkAssignable(e.getExpression().getTypeModel(), kt,
e.getExpression(),
"index must be assignable to key type");
ProducedType rt = unit.getOptionalType(vt);
that.setTypeModel(rt);
}
}
else {
ProducedType rst = pt.getSupertype(unit.getRangedDeclaration());
if (rst==null) {
that.getPrimary().addError("illegal receiving type for index range expression: " +
pt.getDeclaration().getName() + " is not a subtype of Ranged");
}
else {
List<ProducedType> args = rst.getTypeArgumentList();
ProducedType kt = args.get(0);
ProducedType rt = args.get(1);
Tree.ElementRange er = (Tree.ElementRange) that.getElementOrRange();
checkAssignable(er.getLowerBound().getTypeModel(), kt,
er.getLowerBound(),
"lower bound must be assignable to index type");
if (er.getUpperBound()!=null) {
checkAssignable(er.getUpperBound().getTypeModel(), kt,
er.getUpperBound(),
"upper bound must be assignable to index type");
}
if (er.getLength()!=null) {
checkAssignable(er.getLength().getTypeModel(),
unit.getIntegerDeclaration().getType(),
er.getLength(),
"length must be an integer");
}
that.setTypeModel(rt);
}
}
}
}
}
private ProducedType type(Tree.PostfixExpression that) {
Tree.Primary p = that.getPrimary();
return p==null ? null : p.getTypeModel();
}
@Override public void visit(Tree.PostfixOperatorExpression that) {
super.visit(that);
visitIncrementDecrement(that, type(that), that.getTerm());
checkAssignability(that.getTerm(), that);
}
@Override public void visit(Tree.PrefixOperatorExpression that) {
super.visit(that);
visitIncrementDecrement(that, type(that), that.getTerm());
checkAssignability(that.getTerm(), that);
}
private ProducedType checkOperandTypes(ProducedType lhst, ProducedType rhst,
TypeDeclaration td, Node node, String message) {
ProducedType ut = unionType(lhst, rhst, unit);
ProducedType st = producedType(td, ut);
checkAssignable(lhst, st, node, message);
checkAssignable(rhst, st, node, message);
return ut.getSupertype(td);
}
private void visitIncrementDecrement(Tree.Term that,
ProducedType pt, Tree.Term term) {
if (pt!=null) {
ProducedType ot = checkSupertype(pt, unit.getOrdinalDeclaration(),
term, "operand expression must be of ordinal type");
if (ot!=null) {
ProducedType ta = ot.getTypeArgumentList().get(0);
checkAssignable(ta, pt, that,
"result type must be assignable to declared type");
}
that.setTypeModel(pt);
}
}
/*@Override public void visit(Tree.SumOp that) {
super.visit( (Tree.BinaryOperatorExpression) that );
ProducedType lhst = leftType(that);
if (lhst!=null) {
//take into account overloading of + operator
if (lhst.isSubtypeOf(getStringDeclaration().getType())) {
visitBinaryOperator(that, getStringDeclaration());
}
else {
visitBinaryOperator(that, getNumericDeclaration());
}
}
}*/
private void visitComparisonOperator(Tree.BinaryOperatorExpression that,
TypeDeclaration type) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkOperandTypes(lhst, rhst, type, that,
"operand expressions must be comparable");
}
that.setTypeModel( unit.getBooleanDeclaration().getType() );
}
private void visitCompareOperator(Tree.CompareOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkOperandTypes(lhst, rhst, unit.getComparableDeclaration(), that,
"operand expressions must be comparable");
}
that.setTypeModel( unit.getComparisonDeclaration().getType() );
}
private void visitRangeOperator(Tree.RangeOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkOperandTypes(lhst, rhst, unit.getOrdinalDeclaration(), that,
"operand expressions must be of compatible ordinal type");
ProducedType ct = checkOperandTypes(lhst, rhst,
unit.getComparableDeclaration(), that,
"operand expressions must be comparable");
if (ct!=null) {
ProducedType pt = producedType(unit.getRangeDeclaration(),
ct.getTypeArgumentList().get(0));
that.setTypeModel(pt);
}
}
}
private void visitSegmentOperator(Tree.SegmentOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
ProducedType ot = checkSupertype(lhst, unit.getOrdinalDeclaration(),
that.getLeftTerm(), "left operand must be of ordinal type");
checkAssignable(rhst, unit.getIntegerDeclaration().getType(),
that.getRightTerm(), "right operand must be an integer");
if (ot!=null) {
ProducedType ta = ot.getTypeArgumentList().get(0);
ProducedType rt = unit.getEmptyType(unit.getSequenceType(ta));
that.setTypeModel(rt);
}
}
}
private void visitEntryOperator(Tree.EntryOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkSupertype(lhst, unit.getObjectDeclaration(), that.getLeftTerm(),
"operand expression must support equality");
checkSupertype(rhst, unit.getObjectDeclaration(), that.getRightTerm(),
"operand expression must support equality");
ProducedType et = unit.getEntryType(lhst, rhst);
that.setTypeModel(et);
}
}
private void visitArithmeticOperator(Tree.BinaryOperatorExpression that,
TypeDeclaration type) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
ProducedType lhsst = checkSupertype(lhst, type, that.getLeftTerm(),
"operand expression must be of numeric type");
ProducedType rhsst = checkSupertype(rhst, type, that.getRightTerm(),
"operand expression must be of numeric type");
if (rhsst!=null && lhsst!=null) {
rhst = rhsst.getTypeArgumentList().get(0);
lhst = lhsst.getTypeArgumentList().get(0);
//find the common type to which arguments
//can be widened, according to Castable
ProducedType rt;
ProducedType st;
if (lhst.isSubtypeOf(unit.getCastableType(lhst)) &&
rhst.isSubtypeOf(unit.getCastableType(lhst))) {
//the lhs has a wider type
rt = lhst;
st = lhsst;
}
else if (lhst.isSubtypeOf(unit.getCastableType(rhst)) &&
rhst.isSubtypeOf(unit.getCastableType(rhst))) {
//the rhs has a wider type
rt = rhst;
st = rhsst;
}
else if (lhst.isExactly(rhst)) {
//in case the args don't implement Castable at all, but
//they are exactly the same type, so no promotion is
//necessary - note the language spec does not actually
//bless this at present
rt = lhst;
st = lhsst;
}
else {
that.addError("operand expressions must be promotable to common numeric type: " +
lhst.getProducedTypeName() + " and " +
rhst.getProducedTypeName());
return;
}
checkAssignable(rt, producedType(type, rt), that,
"operands must be of compatible numeric type");
that.setTypeModel(rt);
}
}
}
private void visitPowerOperator(Tree.BinaryOperatorExpression that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
ProducedType lhsst = checkSupertype(lhst, unit.getExponentiableDeclaration(),
that.getLeftTerm(), "operand expression must be of exponentiable type");
/*ProducedType rhsst = checkOperandType(rhst, unit.getNumericDeclaration(),
that.getRightTerm(), "operand expression must be of numeric type");*/
if (/*rhsst!=null &&*/lhsst!=null) {
//rhst = rhsst.getTypeArgumentList().get(0);
lhst = lhsst.getTypeArgumentList().get(0);
that.setTypeModel(lhst);
ProducedType powt = lhsst.getTypeArgumentList().get(1);
if (!rhst.isSubtypeOf(unit.getCastableType(powt)) &&
!rhst.isSubtypeOf(powt)) { //note the language spec does not actually bless this
that.getRightTerm().addError("operand expression must be promotable to exponent type: " +
rhst.getProducedTypeName() + " is not promotable to " +
powt.getProducedTypeName());
}
}
}
}
private void visitArithmeticAssignOperator(Tree.BinaryOperatorExpression that,
TypeDeclaration type) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
ProducedType nt = checkSupertype(lhst, type, that.getLeftTerm(),
"operand expression must be of numeric type");
that.setTypeModel(lhst);
if (nt!=null) {
ProducedType t = nt.getTypeArgumentList().get(0);
//that.setTypeModel(t); //stef requests lhst to make it easier on backend
if (!rhst.isSubtypeOf(unit.getCastableType(t)) &&
!rhst.isSubtypeOf(lhst)) { //note the language spec does not actually bless this
that.getRightTerm().addError("operand expression must be promotable to declared type: " +
rhst.getProducedTypeName() + " is not promotable to " +
nt.getProducedTypeName());
}
checkAssignable(t, lhst, that,
"result type must be assignable to declared type");
}
}
}
private void visitSetOperator(Tree.BitwiseOp that) {
//TypeDeclaration sd = unit.getSetDeclaration();
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkAssignable(lhst, unit.getSetType(unit.getObjectDeclaration().getType()),
that.getLeftTerm(), "set operand expression must be a set");
checkAssignable(lhst, unit.getSetType(unit.getObjectDeclaration().getType()),
that.getRightTerm(), "set operand expression must be a set");
ProducedType lhset = unit.getSetElementType(lhst);
ProducedType rhset = unit.getSetElementType(rhst);
ProducedType et;
if (that instanceof Tree.IntersectionOp) {
et = intersectionType(rhset, lhset, unit);
}
else if (that instanceof Tree.ComplementOp) {
et = lhset;
}
else {
et = unionType(rhset, lhset, unit);
}
that.setTypeModel(unit.getSetType(et));
}
}
private void visitSetAssignmentOperator(Tree.BitwiseAssignmentOp that) {
//TypeDeclaration sd = unit.getSetDeclaration();
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkAssignable(lhst, unit.getSetType(unit.getObjectDeclaration().getType()),
that.getLeftTerm(), "set operand expression must be a set");
checkAssignable(lhst, unit.getSetType(unit.getObjectDeclaration().getType()),
that.getRightTerm(), "set operand expression must be a set");
ProducedType lhset = unit.getSetElementType(lhst);
ProducedType rhset = unit.getSetElementType(rhst);
if (that instanceof Tree.UnionAssignOp ||
that instanceof Tree.XorAssignOp) {
checkAssignable(rhset, lhset, that.getRightTerm(),
"resulting set element type must be assignable to to declared set element type");
}
that.setTypeModel(unit.getSetType(lhst)); //in theory, we could make this narrower
}
}
private void visitLogicalOperator(Tree.BinaryOperatorExpression that) {
ProducedType bt = unit.getBooleanDeclaration().getType();
checkAssignable(leftType(that), bt, that,
"logical operand expression must be a boolean value");
checkAssignable(rightType(that), bt, that,
"logical operand expression must be a boolean value");
that.setTypeModel(bt);
}
private void visitDefaultOperator(Tree.DefaultOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkOptional(lhst, that.getLeftTerm(), that.getLeftTerm());
List<ProducedType> list = new ArrayList<ProducedType>();
addToUnion(list, rhst);
addToUnion(list, unit.getDefiniteType(lhst));
if (list.size()==1) {
that.setTypeModel(list.get(0));
}
else {
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
that.setTypeModel(ut.getType());
}
/*that.setTypeModel(rhst);
ProducedType ot;
if (isOptionalType(rhst)) {
ot = rhst;
}
else {
ot = getOptionalType(rhst);
}
if (!lhst.isSubtypeOf(ot)) {
that.getLeftTerm().addError("must be of type: " +
ot.getProducedTypeName());
}*/
}
}
private void visitThenOperator(Tree.ThenOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( lhst!=null ) {
checkAssignable(lhst, unit.getBooleanDeclaration().getType(), that.getLeftTerm(),
"operand expression must be a boolean value");
}
if ( rhst!=null ) {
checkAssignable(rhst, unit.getObjectDeclaration().getType(), that.getRightTerm(),
"operand expression may not be an optional type");
that.setTypeModel(unit.getOptionalType(rhst));
}
}
private void visitInOperator(Tree.InOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if ( rhst!=null && lhst!=null ) {
checkAssignable(lhst, unit.getObjectDeclaration().getType(), that.getLeftTerm(),
"operand expression must support equality");
checkAssignable(rhst, unit.getCategoryDeclaration().getType(), that.getRightTerm(),
"operand expression must be a category");
}
that.setTypeModel( unit.getBooleanDeclaration().getType() );
}
private void visitUnaryOperator(Tree.UnaryOperatorExpression that,
TypeDeclaration type) {
ProducedType t = type(that);
if (t!=null) {
ProducedType nt = checkSupertype(t, type, that.getTerm(),
"operand expression must be of correct type");
if (nt!=null) {
ProducedType at = nt.getTypeArguments().isEmpty() ?
nt : nt.getTypeArgumentList().get(0);
that.setTypeModel(at);
}
}
}
private void visitExistsOperator(Tree.Exists that) {
checkOptional(type(that), that.getTerm(), that);
that.setTypeModel(unit.getBooleanDeclaration().getType());
}
private void visitNonemptyOperator(Tree.Nonempty that) {
checkEmpty(type(that), that.getTerm(), that);
that.setTypeModel(unit.getBooleanDeclaration().getType());
}
private void visitIsOperator(Tree.IsOp that) {
/*checkAssignable( type(that),
getOptionalType(getObjectDeclaration().getType()),
that.getTerm(),
"expression may not be of void type");*/
Tree.Type rt = that.getType();
if (rt!=null) {
ProducedType t = rt.getTypeModel();
if (t!=null) {
checkReified(that, t);
if (that.getTerm()!=null) {
ProducedType pt = that.getTerm().getTypeModel();
if (pt!=null && pt.isSubtypeOf(t)) {
that.addError("expression type is a subtype of the type: " +
pt.getProducedTypeName() + " is assignable to " +
t.getProducedTypeName());
}
else {
ProducedType it = intersectionType(t, pt, unit);
if (it.getDeclaration() instanceof BottomType) {
that.addError("tests assignability to Bottom type: intersection of " +
pt.getProducedTypeName() + " and " +
t.getProducedTypeName() +
" is empty");
}
}
}
}
}
that.setTypeModel(unit.getBooleanDeclaration().getType());
}
private void visitAssignOperator(Tree.AssignOp that) {
ProducedType rhst = rightType(that);
ProducedType lhst = leftType(that);
if ( rhst!=null && lhst!=null ) {
checkAssignable(rhst, lhst, that.getRightTerm(),
"assigned expression must be assignable to declared type");
}
//that.setTypeModel(rhst); //stef requests lhst to make it easier on backend
that.setTypeModel(lhst);
}
private static void checkAssignability(Tree.Term that, Node node) {
if (that instanceof Tree.BaseMemberExpression ||
that instanceof Tree.QualifiedMemberExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) that).getTarget();
if (pr!=null) {
Declaration dec = pr.getDeclaration();
if (!(dec instanceof Value | dec instanceof Getter)) {
node.addError("member cannot be assigned: "
+ dec.getName());
}
else if ( !((TypedDeclaration) dec).isVariable() ) {
node.addError("value is not variable: "
+ dec.getName(), 800);
}
}
}
else {
that.addError("expression cannot be assigned");
}
}
private ProducedType rightType(Tree.BinaryOperatorExpression that) {
Tree.Term rt = that.getRightTerm();
return rt==null? null : rt.getTypeModel();
}
private ProducedType leftType(Tree.BinaryOperatorExpression that) {
Tree.Term lt = that.getLeftTerm();
return lt==null ? null : lt.getTypeModel();
}
private ProducedType type(Tree.UnaryOperatorExpression that) {
Tree.Term t = that.getTerm();
return t==null ? null : t.getTypeModel();
}
@Override public void visit(Tree.ArithmeticOp that) {
super.visit(that);
if (that instanceof Tree.PowerOp) {
visitPowerOperator(that);
}
else {
visitArithmeticOperator(that, getArithmeticDeclaration(that));
}
}
private Interface getArithmeticDeclaration(Tree.ArithmeticOp that) {
if (that instanceof Tree.SumOp) {
return unit.getSummableDeclaration();
}
else if (that instanceof Tree.RemainderOp) {
return unit.getIntegralDeclaration();
}
else {
return unit.getNumericDeclaration();
}
}
private Interface getArithmeticDeclaration(Tree.ArithmeticAssignmentOp that) {
if (that instanceof Tree.AddAssignOp) {
return unit.getSummableDeclaration();
}
else if (that instanceof Tree.RemainderAssignOp) {
return unit.getIntegralDeclaration();
}
else {
return unit.getNumericDeclaration();
}
}
@Override public void visit(Tree.BitwiseOp that) {
super.visit(that);
that.addWarning("Set operators not yet supported");
visitSetOperator(that);
}
@Override public void visit(Tree.LogicalOp that) {
super.visit(that);
visitLogicalOperator(that);
}
@Override public void visit(Tree.EqualityOp that) {
super.visit(that);
visitComparisonOperator(that, unit.getObjectDeclaration());
}
@Override public void visit(Tree.ComparisonOp that) {
super.visit(that);
visitComparisonOperator(that, unit.getComparableDeclaration());
}
@Override public void visit(Tree.IdenticalOp that) {
super.visit(that);
visitComparisonOperator(that, unit.getIdentifiableDeclaration());
}
@Override public void visit(Tree.CompareOp that) {
super.visit(that);
visitCompareOperator(that);
}
@Override public void visit(Tree.DefaultOp that) {
super.visit(that);
visitDefaultOperator(that);
}
@Override public void visit(Tree.ThenOp that) {
super.visit(that);
visitThenOperator(that);
}
@Override public void visit(Tree.NegativeOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getInvertableDeclaration());
}
@Override public void visit(Tree.PositiveOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getInvertableDeclaration());
}
@Override public void visit(Tree.NotOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getBooleanDeclaration());
}
@Override public void visit(Tree.AssignOp that) {
super.visit(that);
visitAssignOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.ArithmeticAssignmentOp that) {
super.visit(that);
visitArithmeticAssignOperator(that, getArithmeticDeclaration(that));
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.LogicalAssignmentOp that) {
super.visit(that);
visitLogicalOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.BitwiseAssignmentOp that) {
super.visit(that);
that.addWarning("Set operators not yet supported");
visitSetAssignmentOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.RangeOp that) {
super.visit(that);
visitRangeOperator(that);
}
@Override public void visit(Tree.SegmentOp that) {
super.visit(that);
visitSegmentOperator(that);
}
@Override public void visit(Tree.EntryOp that) {
super.visit(that);
visitEntryOperator(that);
}
@Override public void visit(Tree.Exists that) {
super.visit(that);
visitExistsOperator(that);
}
@Override public void visit(Tree.Nonempty that) {
super.visit(that);
visitNonemptyOperator(that);
}
@Override public void visit(Tree.IsOp that) {
super.visit(that);
visitIsOperator(that);
}
@Override public void visit(Tree.Extends that) {
super.visit(that);
that.addWarning("extends operator not yet supported");
}
@Override public void visit(Tree.Satisfies that) {
super.visit(that);
that.addWarning("satisfies operator not yet supported");
}
@Override public void visit(Tree.InOp that) {
super.visit(that);
visitInOperator(that);
}
//Atoms:
private void checkOverloadedReference(Tree.MemberOrTypeExpression that) {
if (isAbstraction(that.getDeclaration()) &&
that.getSignature() != null) {
that.addError("ambiguous reference to overloaded method or class: " +
that.getDeclaration().getName());
}
}
@Override public void visit(Tree.BaseMemberExpression that) {
/*if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
super.visit(that);
TypedDeclaration member = getBaseDeclaration(that, that.getSignature());
if (member==null) {
that.addError("method or attribute does not exist or is ambiguous: " +
name(that.getIdentifier()), 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
else {
that.setDeclaration(member);
if (!member.isVisible(that.getScope())) {
that.addError("method or attribute is not visible: " +
name(that.getIdentifier()), 400);
}
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(member, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal);
tal.setTypeModels(ta);
visitBaseMemberExpression(that, member, ta, tal);
//otherwise infer type arguments later
}
else {
//TODO: set the correct metatype
that.setTypeModel(unit.getVoidDeclaration().getType());
}
/*if (defaultArgument) {
if (member.isClassOrInterfaceMember()) {
that.addWarning("references to this from default argument expressions not yet supported");
}
}*/
checkOverloadedReference(that);
}
}
@Override public void visit(Tree.QualifiedMemberExpression that) {
/*that.getPrimary().visit(this);
if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
super.visit(that);
ProducedType pt = that.getPrimary().getTypeModel();
if (pt!=null && that.getIdentifier()!=null &&
!that.getIdentifier().getText().equals("")) {
TypeDeclaration d = unwrap(pt, that).getDeclaration();
TypedDeclaration member = (TypedDeclaration) d.getMember(name(that.getIdentifier()),
unit, that.getSignature());
if (member==null) {
that.addError("member method or attribute does not exist or is ambiguous: " +
name(that.getIdentifier()) +
" in type " + d.getName(), 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
else {
that.setDeclaration(member);
if (!member.isVisible(that.getScope())) {
that.addError("member method or attribute is not visible: " +
name(that.getIdentifier()) +
" of type " + d.getName(), 400);
}
if (member.isProtectedVisibility() &&
!(that.getPrimary() instanceof Tree.This) &&
!(that.getPrimary() instanceof Tree.Super)) {
that.addError("member method or attribute is not visible: " +
name(that.getIdentifier()) +
" of type " + d.getName());
}
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(member,tal, that)) {
List<ProducedType> ta = getTypeArguments(tal);
tal.setTypeModels(ta);
visitQualifiedMemberExpression(that, member, ta, tal);
//otherwise infer type arguments later
}
else {
//TODO: set the correct metatype
that.setTypeModel(unit.getVoidDeclaration().getType());
}
checkOverloadedReference(that);
}
if (that.getPrimary() instanceof Tree.Super) {
if (member!=null && member.isFormal()) {
that.addError("superclass member is formal");
}
}
}
}
private void visitQualifiedMemberExpression(Tree.QualifiedMemberExpression that,
TypedDeclaration member, List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType receivingType = that.getPrimary().getTypeModel();
ProducedType receiverType = unwrap(receivingType, that);
if (acceptsTypeArguments(receiverType, member, typeArgs, tal, that)) {
ProducedTypedReference ptr = receiverType.getTypedMember(member, typeArgs);
/*if (ptr==null) {
that.addError("member method or attribute does not exist: " +
member.getName() + " of type " +
receiverType.getDeclaration().getName());
}
else {*/
ProducedType t = ptr.getFullType(wrap(ptr.getType(), receivingType, that));
that.setTarget(ptr); //TODO: how do we wrap ptr???
that.setTypeModel(t);
}
}
private void visitBaseMemberExpression(Tree.BaseMemberExpression that, TypedDeclaration member,
List<ProducedType> typeArgs, Tree.TypeArguments tal) {
if (acceptsTypeArguments(member, typeArgs, tal, that)) {
ProducedType outerType = that.getScope().getDeclaringType(member);
ProducedTypedReference pr = member.getProducedTypedReference(outerType, typeArgs);
that.setTarget(pr);
ProducedType t = pr.getFullType();
if (isTypeUnknown(t)) {
that.addError("could not determine type of method or attribute reference: " +
name(that.getIdentifier()));
}
else {
that.setTypeModel(t);
}
}
}
@Override public void visit(Tree.BaseTypeExpression that) {
super.visit(that);
/*if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
TypeDeclaration type = getBaseDeclaration(that, that.getSignature());
if (type==null) {
that.addError("type does not exist or is ambiguous: " +
name(that.getIdentifier()), 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
else {
that.setDeclaration(type);
if (!type.isVisible(that.getScope())) {
that.addError("type is not visible: " +
name(that.getIdentifier()), 400);
}
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(type, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal);
tal.setTypeModels(ta);
visitBaseTypeExpression(that, type, ta, tal);
//otherwise infer type arguments later
}
else {
//TODO: set the correct metatype
that.setTypeModel(unit.getVoidDeclaration().getType());
}
checkOverloadedReference(that);
}
}
@Override public void visit(Tree.ExtendedTypeExpression that) {
super.visit(that);
Declaration dec = that.getDeclaration();
if (dec instanceof Class) {
Class c = (Class) dec;
if (c.isAbstraction()) {
//if the constructor is overloaded
//resolve the right overloaded version
Declaration result = dec.getContainer()
.getMemberOrParameter(that.getUnit(), dec.getName(), that.getSignature());
if (result!=null && result!=dec) {
//patch the reference, which was already
//initialized to the abstraction
that.setDeclaration((TypeDeclaration) result);
checkOverloadedReference(that);
}
//else report to user that we could not
//find a matching overloaded constructor
}
}
}
@Override public void visit(Tree.QualifiedTypeExpression that) {
super.visit(that);
/*that.getPrimary().visit(this);
if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
ProducedType pt = that.getPrimary().getTypeModel();
if (that.getPrimary() instanceof Tree.QualifiedTypeExpression ||
that.getPrimary() instanceof Tree.BaseTypeExpression) {
//this is a qualified type name, not member reference
pt = ((Tree.MemberOrTypeExpression) that.getPrimary()).getTarget().getType();
}
if (pt!=null) {
TypeDeclaration d = unwrap(pt, that).getDeclaration();
TypeDeclaration type = (TypeDeclaration) d.getMember(name(that.getIdentifier()),
unit, that.getSignature());
if (type==null) {
that.addError("member type does not exist or is ambiguous: " +
name(that.getIdentifier()) +
" in type " + d.getName(), 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
else {
that.setDeclaration(type);
if (!type.isVisible(that.getScope())) {
that.addError("member type is not visible: " +
name(that.getIdentifier()) +
" of type " + d.getName(), 400);
}
if (type.isProtectedVisibility() &&
!(that.getPrimary() instanceof Tree.This) &&
!(that.getPrimary() instanceof Tree.Super)) {
that.addError("member type is not visible: " +
name(that.getIdentifier()) +
" of type " + d.getName());
}
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(type, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal);
tal.setTypeModels(ta);
visitQualifiedTypeExpression(that, pt, type, ta, tal);
//otherwise infer type arguments later
}
else {
//TODO: set the correct metatype
that.setTypeModel(unit.getVoidDeclaration().getType());
}
checkOverloadedReference(that);
}
//TODO: this is temporary until we get metamodel reference expressions!
if (that.getPrimary() instanceof Tree.BaseTypeExpression ||
that.getPrimary() instanceof Tree.QualifiedTypeExpression) {
ProducedReference target = that.getTarget();
if (target!=null) {
checkTypeBelongsToContainingScope(target.getType(),
that.getScope(), that);
}
}
if (!inExtendsClause && that.getPrimary() instanceof Tree.Super) {
if (type!=null && type.isFormal()) {
that.addError("superclass member class is formal");
}
}
}
}
private boolean explicitTypeArguments(Declaration dec, Tree.TypeArguments tal,
Tree.MemberOrTypeExpression that) {
return !dec.isParameterized() ||
tal instanceof Tree.TypeArgumentList;
//TODO: enable this line to enable
// typechecking of references
// without type arguments
//|| !that.getDirectlyInvoked();
}
@Override public void visit(Tree.SimpleType that) {
//this one is a declaration, not an expression!
//we are only validating type arguments here
super.visit(that);
ProducedType pt = that.getTypeModel();
if (pt!=null) {
TypeDeclaration type = that.getDeclarationModel();//pt.getDeclaration()
Tree.TypeArgumentList tal = that.getTypeArgumentList();
//No type inference for declarations
acceptsTypeArguments(type, getTypeArguments(tal), tal, that);
//the type has already been set by TypeVisitor
}
}
private void visitQualifiedTypeExpression(Tree.QualifiedTypeExpression that,
ProducedType receivingType, TypeDeclaration type,
List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType receiverType = unwrap(receivingType, that);
if (acceptsTypeArguments(receiverType, type, typeArgs, tal, that)) {
ProducedType t = receiverType.getTypeMember(type, typeArgs);
ProducedType ft = isAbstractType(t) ?
unit.getVoidDeclaration().getType() : //TODO: set the correct metatype
t.getFullType(wrap(t, receivingType, that));
that.setTypeModel(ft);
that.setTarget(t);
}
}
private void visitBaseTypeExpression(Tree.BaseTypeExpression that, TypeDeclaration type,
List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType outerType = that.getScope().getDeclaringType(type);
ProducedType t = type.getProducedType(outerType, typeArgs);
if (!type.isAlias()) {
//TODO: remove this awful hack which means
// we can't define aliases for types
// with sequenced type parameters
type = t.getDeclaration();
}
if ( acceptsTypeArguments(type, typeArgs, tal, that) ) {
ProducedType ft = isAbstractType(t) ?
unit.getVoidDeclaration().getType() : //TODO: set the correct metatype
t.getFullType();
that.setTypeModel(ft);
that.setTarget(t);
}
}
private boolean isAbstractType(ProducedType t) {
if (t.getDeclaration() instanceof Class) {
return ((Class) t.getDeclaration()).isAbstract();
}
else if (t.getDeclaration() instanceof TypeParameter) {
return ((TypeParameter) t.getDeclaration()).getParameterList()==null;
}
else {
return true;
}
}
@Override public void visit(Tree.Expression that) {
//i.e. this is a parenthesized expression
super.visit(that);
Tree.Term term = that.getTerm();
if (term==null) {
that.addError("expression not well formed");
}
else {
ProducedType t = term.getTypeModel();
if (t==null) {
//that.addError("could not determine type of expression");
}
else {
that.setTypeModel(t);
}
}
}
@Override public void visit(Tree.SpecifierOrInitializerExpression that) {
//i.e. this is a parenthesized expression
super.visit(that);
Tree.Term term = that.getExpression()==null ?
null : that.getExpression().getTerm();
if (term!=null) {
//TODO: it seems a bit fragile to handle this here
if (term instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression smte = (Tree.StaticMemberOrTypeExpression) term;
if (isGeneric(smte.getDeclaration())) {
if (smte.getTypeArguments() instanceof Tree.InferredTypeArguments) {
smte.addError("missing type arguments to: " +
smte.getDeclaration().getName());
}
}
}
}
}
@Override public void visit(Tree.Outer that) {
ProducedType ci = getOuterClassOrInterface(that.getScope());
if (ci==null) {
that.addError("outer appears outside a nested class or interface definition");
}
else {
that.setTypeModel(ci);
}
if (defaultArgument) {
that.addError("reference to outer from default argument expression");
}
}
private boolean inExtendsClause = false;
@Override public void visit(Tree.Super that) {
if (inExtendsClause) {
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (ci!=null) {
if (ci.isClassOrInterfaceMember()) {
ClassOrInterface s = (ClassOrInterface) ci.getContainer();
ProducedType t = s.getExtendedType();
//TODO: type arguments??
that.setTypeModel(t);
}
}
}
else {
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
//TODO: for consistency, move these errors to SelfReferenceVisitor
if (ci==null) {
that.addError("super appears outside a class definition");
}
else if (!(ci instanceof Class)) {
that.addError("super appears inside an interface definition");
}
else {
ProducedType t = ci.getExtendedType();
//TODO: type arguments
that.setTypeModel(t);
}
}
if (defaultArgument) {
that.addError("reference to super from default argument expression");
}
}
@Override public void visit(Tree.This that) {
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (ci==null) {
that.addError("this appears outside a class or interface definition");
}
else {
that.setTypeModel(ci.getType());
}
/*if (defaultArgument) {
that.addWarning("references to this from default argument expressions not yet supported");
}*/
}
@Override public void visit(Tree.SequenceEnumeration that) {
super.visit(that);
ProducedType st;
if ( that.getExpressionList()==null ) {
st = unit.getEmptyDeclaration().getType();
}
else {
ProducedType et;
List<ProducedType> list = new ArrayList<ProducedType>();
for (Tree.Expression e: that.getExpressionList().getExpressions()) {
if (e.getTypeModel()!=null) {
addToUnion(list, denotableType(e.getTypeModel()));
}
}
if (list.isEmpty()) {
// that.addError("could not infer type of sequence enumeration");
return;
}
else if (list.size()==1) {
et = list.get(0);
}
else {
UnionType ut = new UnionType(unit);
ut.setExtendedType( unit.getObjectDeclaration().getType() );
ut.setCaseTypes(list);
et = ut.getType();
}
st = unit.getSequenceType(et);
}
that.setTypeModel(st);
}
@Override public void visit(Tree.CatchVariable that) {
super.visit(that);
Tree.Variable var = that.getVariable();
if (var!=null) {
ProducedType et = unit.getExceptionDeclaration().getType();
if (var.getType() instanceof Tree.LocalModifier) {
var.getType().setTypeModel(et);
var.getDeclarationModel().setType(et);
}
else {
checkAssignable(var.getType().getTypeModel(), et,
var.getType(),
"catch type must be an exception type");
}
}
}
@Override public void visit(Tree.StringTemplate that) {
super.visit(that);
for (Tree.Expression e: that.getExpressions()) {
checkAssignable(e.getTypeModel(), unit.getObjectDeclaration().getType(), e,
"interpolated expression must be assignable to Object");
}
setLiteralType(that, unit.getStringDeclaration());
}
@Override public void visit(Tree.StringLiteral that) {
setLiteralType(that, unit.getStringDeclaration());
}
@Override public void visit(Tree.NaturalLiteral that) {
setLiteralType(that, unit.getIntegerDeclaration());
}
@Override public void visit(Tree.FloatLiteral that) {
setLiteralType(that, unit.getFloatDeclaration());
}
@Override public void visit(Tree.CharLiteral that) {
setLiteralType(that, unit.getCharacterDeclaration());
}
@Override public void visit(Tree.QuotedLiteral that) {
setLiteralType(that, unit.getQuotedDeclaration());
String fn = that.getUnit().getFilename();
if (!"package.ceylon".equals(fn) && !"module.ceylon".equals(fn)) {
that.addWarning("single-quoted literals are not yet supported");
}
}
private void setLiteralType(Tree.Atom that, TypeDeclaration languageType) {
that.setTypeModel(languageType.getType());
}
@Override
public void visit(Tree.CompilerAnnotation that) {
//don't visit the argument
}
@Override
public void visit(Tree.MatchCase that) {
super.visit(that);
for (Tree.Expression e: that.getExpressionList().getExpressions()) {
ProducedType t = e.getTypeModel();
if (!isTypeUnknown(t)) {
TypeDeclaration dec = t.getDeclaration();
if (!dec.isToplevel() || !dec.isAnonymous()) {
e.addError("case must refer to a toplevel object declaration");
}
if (switchExpression!=null) {
if (!hasUncheckedNulls(switchExpression.getTerm()) || !isNullCase(t)) {
checkAssignable(t, switchExpression.getTypeModel(), e,
"case must be assignable to switch expression type");
}
}
}
}
}
@Override
public void visit(Tree.SatisfiesCase that) {
super.visit(that);
that.addWarning("satisfies cases are not yet supported");
}
@Override
public void visit(Tree.IsCase that) {
Tree.Type t = that.getType();
if (t!=null) {
t.visit(this);
}
Tree.Variable v = that.getVariable();
if (v!=null) {
v.visit(this);
initOriginalDeclaration(v);
}
if (switchExpression!=null) {
ProducedType st = switchExpression.getTypeModel();
if (t!=null && st!=null) {
ProducedType pt = t.getTypeModel();
ProducedType it = intersectionType(pt, st, unit);
if (!hasUncheckedNulls(switchExpression.getTerm()) || !isNullCase(pt)) {
if (it.isExactly(unit.getBottomDeclaration().getType())) {
that.addError("narrows to Bottom type: " +
pt.getProducedTypeName() + " has empty intersection with " +
st.getProducedTypeName());
}
/*checkAssignable(ct, switchType, cc.getCaseItem(),
"case type must be a case of the switch type");*/
}
if (v!=null) {
v.getType().setTypeModel(it);
v.getDeclarationModel().setType(it);
}
}
}
}
@Override
public void visit(Tree.SwitchStatement that) {
Tree.Expression ose = switchExpression;
switchExpression = that.getSwitchClause().getExpression();
super.visit(that);
switchExpression = ose;
}
@Override
public void visit(Tree.SwitchCaseList that) {
super.visit(that);
if (switchExpression!=null) {
boolean hasIsCase = false;
for (Tree.CaseClause cc: that.getCaseClauses()) {
if (cc.getCaseItem() instanceof Tree.IsCase) {
hasIsCase = true;
}
ProducedType ct = getType(cc);
if (!isTypeUnknown(ct)) {
for (Tree.CaseClause occ: that.getCaseClauses()) {
if (occ==cc) break;
ProducedType oct = getType(occ);
if (!isTypeUnknown(oct)) {
//TODO: the following test doesn't work for cases of an interface!
if (!intersectionType(ct, oct, unit)
.isExactly(unit.getBottomDeclaration().getType())) {
cc.getCaseItem().addError("cases are not disjoint: " +
ct.getProducedTypeName() + " and " +
oct.getProducedTypeName());
}
}
}
}
}
if (hasIsCase) {
Tree.Term st = switchExpression.getTerm();
if (st instanceof Tree.BaseMemberExpression) {
checkReferenceIsNonVariable((Tree.BaseMemberExpression) st);
}
else {
switchExpression.addError("switch expression must be a value reference in switch with type cases");
}
}
}
if (that.getElseClause()==null && switchExpression!=null) {
ProducedType st = switchExpression.getTypeModel();
if (st!=null) {
//form the union of all the case types
List<ProducedType> list = new ArrayList<ProducedType>();
for (Tree.CaseClause cc: that.getCaseClauses()) {
ProducedType ct = getType(cc);
if (isTypeUnknown(ct)) {
return; //Note: early exit!
}
else {
addToUnion(list, ct);
}
}
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
//if the union of the case types covers
//the switch expression type then the
//switch is exhaustive
if (!ut.getType().covers(st)) {
that.addError("case types must cover all cases of the switch type or an else clause must appear: " +
ut.getType().getProducedTypeName() + " does not cover " + st.getProducedTypeName());
}
}
}
}
private boolean isNullCase(ProducedType ct) {
TypeDeclaration d = ct.getDeclaration();
return d!=null &&
d.equals(unit.getNothingDeclaration()) &&
d.equals(unit.getNullDeclaration());
}
private ProducedType getType(Tree.CaseClause cc) {
Tree.CaseItem ci = cc.getCaseItem();
if (ci instanceof Tree.IsCase) {
Tree.Type t = ((Tree.IsCase) ci).getType();
if (t!=null) {
return t.getTypeModel().getUnionOfCases(true);
}
else {
return null;
}
}
else if (ci instanceof Tree.MatchCase) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (Tree.Expression e: ((Tree.MatchCase) ci).getExpressionList().getExpressions()) {
if (e.getTypeModel()!=null) {
addToUnion(list, e.getTypeModel());
}
}
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
return ut.getType();
}
else {
return null;
}
}
@Override
public void visit(Tree.TryCatchStatement that) {
super.visit(that);
for (Tree.CatchClause cc: that.getCatchClauses()) {
if (cc.getCatchVariable()!=null &&
cc.getCatchVariable().getVariable()!=null) {
ProducedType ct = cc.getCatchVariable()
.getVariable().getType().getTypeModel();
if (ct!=null) {
for (Tree.CatchClause ecc: that.getCatchClauses()) {
if (ecc.getCatchVariable()!=null &&
ecc.getCatchVariable().getVariable()!=null) {
if (cc==ecc) break;
ProducedType ect = ecc.getCatchVariable()
.getVariable().getType().getTypeModel();
if (ect!=null) {
if (ct.isSubtypeOf(ect)) {
cc.getCatchVariable().getVariable().getType()
.addError("exception type is already handled by earlier catch clause:"
+ ct.getProducedTypeName());
}
if (ct.getDeclaration() instanceof UnionType) {
for (ProducedType ut: ct.getDeclaration().getCaseTypes()) {
if ( ut.substitute(ct.getTypeArguments()).isSubtypeOf(ect) ) {
cc.getCatchVariable().getVariable().getType()
.addError("exception type is already handled by earlier catch clause: "
+ ut.getProducedTypeName());
}
}
}
}
}
}
}
}
}
}
private static boolean acceptsTypeArguments(Declaration member, List<ProducedType> typeArguments,
Tree.TypeArguments tal, Node parent) {
return acceptsTypeArguments(null, member, typeArguments, tal, parent);
}
private static boolean isGeneric(Declaration member) {
return member instanceof Generic &&
!((Generic) member).getTypeParameters().isEmpty();
}
private static boolean acceptsTypeArguments(ProducedType receiver, Declaration member,
List<ProducedType> typeArguments, Tree.TypeArguments tal, Node parent) {
if (member==null) return false;
if (isGeneric(member)) {
List<TypeParameter> params = ((Generic) member).getTypeParameters();
if ( params.size()==typeArguments.size() ) {
for (int i=0; i<params.size(); i++) {
TypeParameter param = params.get(i);
ProducedType argType = typeArguments.get(i);
//Map<TypeParameter, ProducedType> self = Collections.singletonMap(param, arg);
for (ProducedType st: param.getSatisfiedTypes()) {
//sts = sts.substitute(self);
ProducedType sts = st.getProducedType(receiver, member, typeArguments);
if (argType!=null) {
if (!argType.isSubtypeOf(sts)) {
if (tal instanceof Tree.InferredTypeArguments) {
parent.addError("inferred type argument " + argType.getProducedTypeName()
+ " to type parameter " + param.getName()
+ " of declaration " + member.getName()
+ " not assignable to " + sts.getProducedTypeName());
}
else {
( (Tree.TypeArgumentList) tal ).getTypes()
.get(i).addError("type parameter " + param.getName()
+ " of declaration " + member.getName()
+ " has argument " + argType.getProducedTypeName()
+ " not assignable to " + sts.getProducedTypeName());
}
return false;
}
}
}
boolean asec = argumentSatisfiesEnumeratedConstraint(receiver, member,
typeArguments, argType, param);
if (!asec) {
if (tal instanceof Tree.InferredTypeArguments) {
parent.addError("inferred type argument " + argType.getProducedTypeName()
+ " to type parameter " + param.getName()
+ " of declaration " + member.getName()
+ " not one of the enumerated cases");
}
else {
( (Tree.TypeArgumentList) tal ).getTypes()
.get(i).addError("type parameter " + param.getName()
+ " of declaration " + member.getName()
+ " has argument " + argType.getProducedTypeName()
+ " not one of the enumerated cases");
}
return false;
}
}
return true;
}
else {
if (tal==null || tal instanceof Tree.InferredTypeArguments) {
parent.addError("requires type arguments: " + member.getName());
}
else {
tal.addError("wrong number of type arguments to: " + member.getName());
}
return false;
}
}
else {
boolean empty = typeArguments.isEmpty();
if (!empty) {
tal.addError("does not accept type arguments: " +
member.getName());
}
return empty;
}
}
private static boolean argumentSatisfiesEnumeratedConstraint(ProducedType receiver,
Declaration member, List<ProducedType> typeArguments, ProducedType argType,
TypeParameter param) {
List<ProducedType> caseTypes = param.getCaseTypes();
if (caseTypes==null) {
//no enumerated constraint
return true;
}
//if the type argument is a subtype of one of the cases
//of the type parameter then the constraint is satisfied
for (ProducedType ct: caseTypes) {
ProducedType cts = ct.getProducedType(receiver, member, typeArguments);
if (argType.isSubtypeOf(cts)) {
return true;
}
}
//if the type argument is itself a type parameter with
//an enumerated constraint, and every enumerated case
//is a subtype of one of the cases of the type parameter,
//then the constraint is satisfied
if (argType.getDeclaration() instanceof TypeParameter) {
List<ProducedType> argCaseTypes = argType.getDeclaration().getCaseTypes();
if (argCaseTypes!=null) {
for (ProducedType act: argCaseTypes) {
boolean foundCase = false;
for (ProducedType ct: caseTypes) {
ProducedType cts = ct.getProducedType(receiver, member, typeArguments);
if (act.isSubtypeOf(cts)) {
foundCase = true;
break;
}
}
if (!foundCase) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public void visit(Tree.ExtendedType that) {
inExtendsClause = true;
super.visit(that);
inExtendsClause = false;
TypeDeclaration td = (TypeDeclaration) that.getScope();
Tree.SimpleType et = that.getType();
if (et!=null) {
ProducedType type = et.getTypeModel();
if (type!=null) {
checkSelfTypes(et, td, type);
checkExtensionOfMemberType(et, td, type);
//checkCaseOfSupertype(et, td, type);
}
}
}
@Override
public void visit(Tree.SatisfiedTypes that) {
super.visit(that);
TypeDeclaration td = (TypeDeclaration) that.getScope();
for (Tree.StaticType t: that.getTypes()) {
ProducedType type = t.getTypeModel();
if (type!=null) {
checkSelfTypes(t, td, type);
checkExtensionOfMemberType(t, td, type);
/*if (!(td instanceof TypeParameter)) {
checkCaseOfSupertype(t, td, type);
}*/
}
}
}
/*void checkCaseOfSupertype(Tree.StaticType t, TypeDeclaration td,
ProducedType type) {
//TODO: I think this check is a bit too restrictive, since
// it doesn't allow intermediate types between the
// enumerated type and the case type, but since the
// similar check below doesn't work, we need it
if (type.getDeclaration().getCaseTypes()!=null) {
for (ProducedType ct: type.getDeclaration().getCaseTypes()) {
if (ct.substitute(type.getTypeArguments())
.isExactly(td.getType())) {
return;
}
}
t.addError("not a case of supertype: " +
type.getDeclaration().getName());
}
}*/
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
//this forces every case to be a subtype of the
//enumerated type, so that we can make use of the
//enumerated type is equivalent to its cases
TypeDeclaration td = (TypeDeclaration) that.getScope();
//TODO: get rid of this awful hack:
List<ProducedType> cases = td.getCaseTypes();
td.setCaseTypes(null);
if (!(td instanceof TypeParameter)) {
for (Tree.StaticType t: that.getTypes()) {
ProducedType type = t.getTypeModel();
if (!(type.getDeclaration() instanceof TypeParameter)) {
//it's not a self type
if (type!=null) {
checkAssignable(type, td.getType(), t,
"case type must be a subtype of enumerated type");
//note: this is a better, faster way to call
// validateEnumeratedSupertypeArguments()
// but unfortunately it winds up displaying
// the error on the wrong node, confusing
// the user
/*ProducedType supertype = type.getDeclaration().getType().getSupertype(td);
validateEnumeratedSupertypeArguments(t, type.getDeclaration(), supertype);*/
}
}
}
for (Tree.BaseMemberExpression bme: that.getBaseMemberExpressions()) {
ProducedType type = bme.getTypeModel();
if (type!=null) {
checkAssignable(type, td.getType(), bme,
"case type must be a subtype of enumerated type");
}
}
}
//TODO: get rid of this awful hack:
td.setCaseTypes(cases);
}
private void checkExtensionOfMemberType(Node that, TypeDeclaration td,
ProducedType type) {
ProducedType qt = type.getQualifyingType();
if (qt!=null && td instanceof ClassOrInterface) {
Scope s = td;
while (s!=null) {
s = s.getContainer();
if (s instanceof TypeDeclaration) {
TypeDeclaration otd = (TypeDeclaration) s;
if ( otd.getType().isSubtypeOf(qt) ) {
return;
}
}
}
that.addError("containing type " + qt.getDeclaration().getName() +
" of supertype " + type.getDeclaration().getName() +
" is not an outer type or supertype of any outer type of " +
td.getName());
}
}
private void checkSelfTypes(Node that, TypeDeclaration td, ProducedType type) {
if (!(td instanceof TypeParameter)) { //TODO: is this really ok?!
List<TypeParameter> params = type.getDeclaration().getTypeParameters();
List<ProducedType> args = type.getTypeArgumentList();
for (int i=0; i<params.size(); i++) {
TypeParameter param = params.get(i);
if ( param.isSelfType() && args.size()>i ) {
ProducedType arg = args.get(i);
TypeDeclaration std = param.getSelfTypedDeclaration();
ProducedType at;
if (param.getContainer().equals(std)) {
at = td.getType();
}
else {
//TODO: lots wrong here?
TypeDeclaration mtd = (TypeDeclaration) td.getMember(std.getName(), null);
at = mtd==null ? null : mtd.getType();
}
if (at!=null) {
checkAssignable(at, arg, std, that,
"type argument does not satisfy self type constraint on type parameter " +
param.getName() + " of " + type.getDeclaration().getName());
}
}
}
}
}
private void validateEnumeratedSupertypes(Node that, Class d) {
ProducedType type = d.getType();
for (ProducedType supertype: type.getSupertypes()) {
if (!type.isExactly(supertype)) {
TypeDeclaration std = supertype.getDeclaration();
if (std.getCaseTypes()!=null) {
List<ProducedType> types=new ArrayList<ProducedType>();
for (ProducedType ct: std.getCaseTypes()) {
ProducedType cst = type.getSupertype(ct.getDeclaration());
if (cst!=null) {
types.add(cst);
}
}
if (types.isEmpty()) {
that.addError("concrete type is not a subtype of any case of enumerated supertype: " +
d.getName() + " is a subtype of " + std.getName());
}
else if (types.size()>1) {
StringBuilder sb = new StringBuilder();
for (ProducedType pt: types) {
sb.append(pt.getProducedTypeName()).append(" and ");
}
sb.setLength(sb.length()-5);
that.addError("concrete type is a subtype of multiple cases of enumerated supertype: " +
d.getName() + " is a subtype of " + sb);
}
}
}
}
}
private void validateEnumeratedSupertypeArguments(Node that, ClassOrInterface d) {
//note: I hate doing the whole traversal here, but it is the
// only way to get the error in the right place (see
// the note in visit(CaseTypes) for more)
ProducedType type = d.getType();
for (ProducedType supertype: type.getSupertypes()) { //traverse the entire supertype hierarchy of the declaration
if (!type.isExactly(supertype)) {
List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations();
if (ctds!=null) {
for (TypeDeclaration ct: ctds) {
if (ct.equals(d)) { //the declaration is a case of the current enumerated supertype
validateEnumeratedSupertypeArguments(that, d, supertype);
break;
}
}
}
}
}
}
private void validateEnumeratedSupertypeArguments(Node that, TypeDeclaration d,
ProducedType supertype) {
for (TypeParameter p: supertype.getDeclaration().getTypeParameters()) {
ProducedType arg = supertype.getTypeArguments().get(p); //the type argument that the declaration (indirectly) passes to the enumerated supertype
if (arg!=null) {
validateEnumeratedSupertypeArgument(that, d, supertype, p, arg);
}
}
}
private void validateEnumeratedSupertypeArgument(Node that, TypeDeclaration d,
ProducedType supertype, TypeParameter p, ProducedType arg) {
TypeDeclaration td = arg.getDeclaration();
if (td instanceof TypeParameter) {
TypeParameter tp = (TypeParameter) td;
if (tp.getDeclaration().equals(d)) { //the argument is a type parameter of the declaration
//check that the variance of the argument type parameter is
//the same as the type parameter of the enumerated supertype
if (p.isCovariant() && !tp.isCovariant()) {
that.addError("argument to covariant type parameter of supertype must be covariant: " +
p.getName() + " of "+ supertype.getDeclaration().getName());
}
if (p.isContravariant() && !tp.isContravariant()) {
that.addError("argument to contravariant type parameter of supertype must be contravariant: " +
p.getName() + " of "+ supertype.getDeclaration().getName());
}
}
else {
that.addError("argument to type parameter of enumerated supertype must be a type parameter of " +
d.getName() + ": " + p.getName() + " of "+ supertype.getDeclaration().getName());
}
}
else if (p.isCovariant()) {
if (!(td instanceof BottomType)) {
//TODO: let it be the union of the lower bounds on p
that.addError("argument to covariant type parameter of enumerated supertype must be a type parameter or Bottom: " +
p.getName() + " of "+ supertype.getDeclaration().getName());
}
}
else if (p.isContravariant()) {
if (!(td.equals(unit.getVoidDeclaration()))) {
//TODO: let it be the intersection of the upper bounds on p
that.addError("argument to contravariant type parameter of enumerated supertype must be a type parameter or Void" +
p.getName() + " of "+ supertype.getProducedTypeName());
}
}
else {
that.addError("argument to type parameter of enumerated supertype must be a type parameter: " +
p.getName() + " of "+ supertype.getDeclaration().getName());
}
}
@Override public void visit(Tree.Term that) {
super.visit(that);
if (that.getTypeModel()==null) {
that.setTypeModel( defaultType() );
}
}
@Override public void visit(Tree.Type that) {
super.visit(that);
if (that.getTypeModel()==null) {
that.setTypeModel( defaultType() );
}
}
private ProducedType defaultType() {
TypeDeclaration ut = new UnknownType(unit);
ut.setExtendedType(unit.getVoidDeclaration().getType());
return ut.getType();
}
}
|
package hr.unidu.oop.p02;
/**
* Primjer stvaranja jednog objekta, pristup varijablama
* i metodama stvorenog objekta.
*/
public class Upoznavanje {
public static void main(String[] args) {
// Deklarira se varijabla referenca za pristup
// objektu tipa Osoba
Osoba susjed;
// Stvara se novi objekt tipa Osoba pomou operatora new.
// Prethodno deklarirana referenca susjed povezuje se sa
// stvorenim objektom.
susjed = new Osoba();
// Osoba susjed = new Osoba();
susjed.ime = "Ivo";
susjed.starost = 37;
// Ispisuje se ime prijatelja (sadraj varijable ime objekta).
System.out.println("Dobar dan, ja sam " + susjed.ime);
// Poziva se metoda rodjendan() koja mijenja starost susjeda.
susjed.upoznavanje();
System.out.println("Danas mi je roendan i imam " + susjed.starost+" godina.");
}
}
|
package com.redhat.ceylon.compiler.typechecker.analyzer;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public class RefinementVisitor extends Visitor {
@Override public void visit(Tree.Declaration that) {
super.visit(that);
Declaration dec = that.getDeclarationModel();
if (dec!=null) {
boolean toplevel = dec.getContainer() instanceof Package;
boolean member = (dec.getContainer() instanceof ClassOrInterface) &&
!(dec instanceof Parameter) &&
!(dec instanceof TypeParameter); //TODO: what about nested interfaces and abstract classes?!
if (!toplevel && !member) {
if (dec.isShared()) {
that.addError("shared declaration is not a member of a class, interface, or package");
}
}
boolean mayBeShared =
dec instanceof MethodOrValue ||
dec instanceof ClassOrInterface;
if (!mayBeShared) {
if (dec.isShared()) {
that.addError("shared member is not a method, attribute, class, or interface");
}
}
boolean mayBeRefined =
dec instanceof Getter ||
dec instanceof Value ||
dec instanceof Method ||
dec instanceof Class;
if (!mayBeRefined) {
checkNonrefinableDeclaration(that, dec);
}
if (!member) {
checkNonMember(that, dec);
}
if ( !dec.isShared() ) {
checkUnshared(that, dec);
}
if (member) {
checkMember(that, dec);
}
}
}
private void checkMember(Tree.Declaration that, Declaration dec) {
ClassOrInterface ci = (ClassOrInterface) dec.getContainer();
if (dec.isFormal() && (ci instanceof Class)) {
Class c = (Class) ci;
if (!c.isAbstract() && !c.isFormal()) {
that.addError("formal member belongs to non-abstract, non-formal class");
}
}
List<Declaration> others = ci.getInheritedMembers( dec.getName() );
if (others.isEmpty()) {
if (dec.isActual()) {
that.addError("actual member does not refine any inherited member");
}
}
else {
for (Declaration refined: others) {
if (!dec.isActual()) {
that.addError("non-actual member refines an inherited member");
}
if (!refined.isDefault() && !refined.isFormal()) {
that.addError("member refines a non-default, non-formal member");
}
if (dec instanceof TypedDeclaration) {
TypedDeclaration tdec = (TypedDeclaration) dec;
ProducedType type = tdec.getType();
TypedDeclaration trefined = (TypedDeclaration) refined;
ProducedType refinedType = trefined.getType();
if (type!=null) {
if (refinedType==null) {
that.addError("could not determine type of refined member");
}
else if (!type.isSubtypeOf(refinedType)) {
((Tree.TypedDeclaration) that).getType().addError(
"member type is not a subtype of refined member type: " +
type.getProducedTypeName() + " is not " +
refinedType.getProducedTypeName());
}
}
if (dec instanceof Method) {
if (!(refined instanceof Method)) {
that.addError("method refines an attribute");
}
else {
ParameterList params = ((Method) dec).getParameterLists().get(0);
ParameterList refinedParams = ((Method) refined).getParameterLists().get(0);
checkParameterTypes(that, params, refinedParams);
}
}
else {
if (refined instanceof Method) {
that.addError("attribute refines a method");
}
else {
if (trefined.isVariable() && !tdec.isVariable()) {
that.addError("non-variable attribute refines a variable attribute");
}
}
}
}
else if (dec instanceof Class) {
if (!(refined instanceof Class)) {
that.addError("refined declaration is not a class");
}
else {
ProducedType type = ((Class) dec).getType();
ProducedType refinedType = ((Class) refined).getType();
if (!type.isSubtypeOf(refinedType)) {
that.addError("member class is not a subclass of refined class: " +
dec.getName() + " is not " +
refined.getName());
}
ParameterList params = ((Class) dec).getParameterList();
ParameterList refinedParams = ((Class) refined).getParameterList();
checkParameterTypes(that, params, refinedParams);
}
}
}
if (others.size()>1) {
//TODO: this is broken for recursive refinement
that.addError("member refines multiple inherited members");
}
}
}
private void checkUnshared(Tree.Declaration that, Declaration dec) {
if (dec.isActual()) {
that.addError("actual member is not shared");
}
if (dec.isFormal()) {
that.addError("formal member is not shared");
}
if (dec.isDefault()) {
that.addError("default member is not shared");
}
}
private void checkNonrefinableDeclaration(Tree.Declaration that,
Declaration dec) {
if (dec.isActual()) {
that.addError("actual declaration is not a getter, simple attribute, or class");
}
if (dec.isFormal()) {
that.addError("formal declaration is not a getter, simple attribute, or class");
}
if (dec.isDefault()) {
that.addError("default declaration is not a getter, simple attribute, or class");
}
}
private void checkNonMember(Tree.Declaration that, Declaration dec) {
if (dec.isActual()) {
that.addError("actual declaration is not a member of a class, interface, or package");
}
if (dec.isFormal()) {
that.addError("formal declaration is not a member of a class, interface, or package");
}
if (dec.isDefault()) {
that.addError("default declaration is not a member of a class, interface, or package");
}
}
private void checkParameterTypes(Tree.Declaration that,
ParameterList params, ParameterList refinedParams) {
if (params.getParameters().size()!=refinedParams.getParameters().size()) {
that.addError("member does not have the same number of parameters as the member it refines");
}
else {
for (int i=0; i<params.getParameters().size(); i++) {
ProducedType refinedParameterType = refinedParams.getParameters().get(i).getType();
ProducedType parameterType = params.getParameters().get(i).getType();
Tree.Type type = getParameterList(that).getParameters().get(i).getType(); //some kind of syntax error
if (type!=null) {
if (refinedParameterType==null || parameterType==null) {
type.addError("could not determine if parameter type is the same as the corresponding parameter of refined member");
}
else if (!parameterType.isExactly(refinedParameterType)) {
//TODO: consider type parameter substitution!!!
type.addError("type of parameter " +
params.getParameters().get(i).getName() + " is different to type of corresponding parameter " +
refinedParams.getParameters().get(i).getName() + " of refined member: " +
parameterType.getProducedTypeName() + " is not exactly " +
refinedParameterType.getProducedTypeName());
}
}
}
}
}
private static Tree.ParameterList getParameterList(Tree.Declaration that) {
Tree.ParameterList pl;
if (that instanceof Tree.AnyMethod) {
pl = ((Tree.AnyMethod) that).getParameterLists().get(0);
}
else {
pl = ((Tree.ClassDefinition) that).getParameterList();
}
return pl;
}
}
|
package com.twitter.intellij.pants.macro;
import com.intellij.ide.macro.Macro;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.twitter.intellij.pants.util.PantsUtil;
import java.util.Optional;
public class FilePathRelativeToBuiltRootMacro extends Macro {
/**
* @return corresponding name of this macro
*/
@Override
public String getName() {
return "PantsFilePathRelativeToBuildRoot";
}
@Override
public String getDescription() {
return "Relative path from build root";
}
@Override
public String expand(final DataContext dataContext) {
VirtualFile fileSelected = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
if (fileSelected == null) {
return null;
}
Optional<VirtualFile> buildRoot = PantsUtil.findBuildRoot(fileSelected);
if (!buildRoot.isPresent()) {
return null;
}
return FileUtil.getRelativePath(VfsUtil.virtualToIoFile(buildRoot.get()), VfsUtil.virtualToIoFile(fileSelected));
}
}
|
package de.espend.idea.php.drupal.references;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.*;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteReference;
import fr.adrienbrault.idea.symfony2plugin.util.MethodMatcher;
import org.jetbrains.annotations.NotNull;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpRouteReferenceContributor extends PsiReferenceContributor {
public static MethodMatcher.CallToSignature[] GENERATOR_SIGNATURES = new MethodMatcher.CallToSignature[] {
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Routing\\UrlGeneratorInterface", "getPathFromRoute"), // <- <@TODO: remove: pre Drupal8 beta
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Routing\\UrlGeneratorInterface", "generateFromRoute"), // <- <@TODO: remove: pre Drupal8 beta
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Routing\\UrlGenerator", "getPathFromRoute"),
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Routing\\UrlGenerator", "generateFromRoute"),
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Url", "fromRoute"),
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Form\\FormStateInterface", "setRedirect"), // @TODO parameter
};
@Override
public void registerReferenceProviders(PsiReferenceRegistrar psiReferenceRegistrar) {
psiReferenceRegistrar.registerReferenceProvider(
PlatformPatterns.psiElement(StringLiteralExpression.class).withLanguage(PhpLanguage.INSTANCE),
new PsiReferenceProvider() {
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return new PsiReference[0];
}
if (MethodMatcher.getMatchedSignatureWithDepth(psiElement, GENERATOR_SIGNATURES) == null) {
return new PsiReference[0];
}
return new PsiReference[]{ new RouteReference((StringLiteralExpression) psiElement) };
}
}
);
psiReferenceRegistrar.registerReferenceProvider(
PlatformPatterns.psiElement(StringLiteralExpression.class).withLanguage(PhpLanguage.INSTANCE),
new PsiReferenceProvider() {
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return new PsiReference[0];
}
if(psiElement instanceof StringLiteralExpression) {
PsiElement parameterList = psiElement.getParent();
if(parameterList instanceof ParameterList) {
PsiElement newExpression = parameterList.getParent();
if(newExpression instanceof NewExpression) {
ClassReference classReference = ((NewExpression) newExpression).getClassReference();
if(classReference != null && "Url".equals(classReference.getName())) {
String fqn = classReference.getFQN();
if(fqn != null && fqn.equals("\\Drupal\\Core\\Url")) {
return new PsiReference[]{ new RouteReference((StringLiteralExpression) psiElement) };
}
}
}
}
}
return new PsiReference[0];
}
}
);
}
}
|
package de.fau.cs.mad.gamekobold.templatebrowser;
import java.io.File;
import de.fau.cs.mad.gamekobold.R;
import de.fau.cs.mad.gamekobold.colorpicker.ColorPickerDialog;
import de.fau.cs.mad.gamekobold.colorpicker.ColorPickerDialogInterface;
import de.fau.cs.mad.gamekobold.jackson.CharacterSheet;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CharacterDetailsActivity extends Activity implements ColorPickerDialogInterface{
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;
private RelativeLayout relLayout;
private CharacterSheet sheet;
private Uri iconUri;
private ImageButton characterIconButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_character_details);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
relLayout = (RelativeLayout)findViewById(R.id.relativeLayout1);
final EditText description = (EditText)findViewById(R.id.editText1);
final Button colorChangeButton = (Button)findViewById(R.id.button2);
final TextView characterName = (TextView)findViewById(R.id.textView1);
final TextView levelLabel = (TextView)findViewById(R.id.textView3);
characterIconButton = (ImageButton)findViewById(R.id.imageButton1);
characterIconButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(CharacterDetailsActivity.this,
android.R.layout.select_dialog_item, getResources()
.getStringArray(R.array.image_picker_items));
AlertDialog.Builder builder = new AlertDialog.Builder(CharacterDetailsActivity.this);
builder.setTitle(getResources().getString(R.string.add_icon));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// create an intent to open Camera app
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// TODO use tmp file functions?
// TODO save file in app folder
// create temporary file to hold the image from Camera.
File file = new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
iconUri = Uri.fromFile(file);
try {
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
iconUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
} else {
// if user choose to select image from sdcard, start the
// intent to open image chooser dialog.
// the image chooser dialog will display list File Manager
// (if exist) apps and default Gallery app.
Intent intent = new Intent();
/*if (id == R.id.action_settings) {
return true;
}*/
if(id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
// callback for ColorPickerDialog
@Override
public void onColorPicked(int color) {
Log.d("CharacterDetails", "picked color:"+color);
setCharacterColor(color);
}
private void setCharacterColor(int color) {
relLayout.setBackgroundColor(color);
if(sheet != null) {
sheet.color = color;
}
}
@Override
// to handle the selected image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
// get the uri of selected image
iconUri = data.getData();
// Assume user selects the image from sdcard using Gallery app. The
// uri from Gallery app does not give the real path to selected
// image, so it has to be resolved on content provider. Method
// getRealPathFromURI used to resolve the real path from the uri.
path = getRealPathFromURI(iconUri); // from Gallery
// If the path is null, assume user selects the image using File
// Manager app. File Manager app returns different information than
// Gallery app. To get the real path to selected image, use
// getImagePath method from the uri
if (path == null)
path = iconUri.getPath(); // from File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
}
else if(requestCode == PICK_FROM_CAMERA){
// If user choose to take picture from camera, get the real path of
// temporary file
//path = iconUri.getPath();
//bitmap = BitmapFactory.decodeFile(path);
// gets the thumbnail
final Bundle extras = data.getExtras();
bitmap = (Bitmap)extras.get("data");
}
if(bitmap != null) {
characterIconButton.setImageBitmap(bitmap);
}
// TODO store image path for later use
}
// TODO refactoring?
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null,
null, null);
if (cursor == null)
return null;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
} else
return null;
}
}
|
package dr.app.beagle.evomodel.branchmodel.lineagespecific;
import dr.app.beagle.evomodel.branchmodel.BranchModel;
import dr.app.beagle.evomodel.branchmodel.HomogeneousBranchModel;
import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel;
import dr.app.beagle.evomodel.substmodel.FrequencyModel;
import dr.app.beagle.evomodel.substmodel.MG94CodonModel;
import dr.app.beagle.evomodel.substmodel.SubstitutionModel;
import dr.app.beagle.evomodel.treelikelihood.BeagleTreeLikelihood;
import dr.app.beagle.evomodel.treelikelihood.PartialsRescalingScheme;
import dr.app.beagle.tools.BeagleSequenceSimulator;
import dr.app.beagle.tools.Partition;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.ConvertAlignment;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.GeneticCode;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.io.NewickImporter;
import dr.evolution.tree.NodeRef;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.CountableBranchCategoryProvider;
import dr.evomodel.branchratemodel.DefaultBranchRateModel;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.inference.model.Variable.ChangeType;
import dr.math.MathUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
public class BranchSpecific extends AbstractModel implements BranchModel {
private boolean setupMapping = true;
private Map<NodeRef, Mapping> nodeMap = new HashMap<NodeRef, Mapping>();
private List<SubstitutionModel> substitutionModels;
// private SubstitutionModel substitutionModel;
private TreeModel treeModel;
private CountableBranchCategoryProvider uCategoriesProvider;
private Parameter uCategoriesParameter;
public BranchSpecific(TreeModel treeModel,
// SubstitutionModel substitutionModel, //
List<SubstitutionModel> substitutionModels,
CountableBranchCategoryProvider uCategoriesProvider,
Parameter uCategoriesParameter
) {
super("");
this.treeModel = treeModel;
this.substitutionModels = substitutionModels;
this.uCategoriesProvider = uCategoriesProvider;
this.uCategoriesParameter = uCategoriesParameter;
// substitutionModels = new ArrayList<SubstitutionModel>();
// FrequencyModel freqModel = substitutionModel.getFrequencyModel();
// for (int i = 0; i < uParameter.getDimension(); i++) {
// double uValue = uParameter.getParameterValue(i);
// double alphaValue = ((MG94CodonModel) substitutionModel).getAlpha();
// double betaValue = ((MG94CodonModel) substitutionModel).getBeta();
// Parameter alphaParameter = new Parameter.Default(1, alphaValue * uValue );
// Parameter betaParameter = new Parameter.Default(1, betaValue * uValue );
// MG94CodonModel mg94 = new MG94CodonModel(Codons.UNIVERSAL, alphaParameter, betaParameter,
// freqModel);
// substitutionModels.add(mg94);
}// END: Constructor
@Override
public Mapping getBranchModelMapping(NodeRef branch) {
if (setupMapping) {
setupNodeMap(branch);
}
return nodeMap.get(branch);
}//END: getBranchModelMapping
public void setupNodeMap(NodeRef branch) {
int branchCategory = uCategoriesProvider.getBranchCategory(treeModel, branch);
final int uCategory = (int) uCategoriesParameter.getParameterValue(branchCategory);
System.out.println(uCategory);
// TODO How about: return new Mapping() that points to uCategory?
// getSubstitutionModels();
nodeMap.put(branch, new Mapping() {
@Override
public int[] getOrder() {
return new int[]{uCategory};
}
@Override
public double[] getWeights() {
return new double[]{1.0};
}
});
}// END: setupNodeMap
@Override
public List<SubstitutionModel> getSubstitutionModels() {
// ArrayList<SubstitutionModel> list = new ArrayList<SubstitutionModel>();
// list.add(substitutionModel);
// return list;
return substitutionModels;
}
@Override
public SubstitutionModel getRootSubstitutionModel() {
// NodeRef root = treeModel.getRoot();
// int rootCategory = uCategoriesProvider.getBranchCategory(treeModel, root);
// rootCategory = (int) uCategoriesParameter.getParameterValue(rootCategory);
int rootCategory = 0;
return substitutionModels.get(rootCategory);
}
@Override
public FrequencyModel getRootFrequencyModel() {
return getRootSubstitutionModel().getFrequencyModel();
}
@Override
public boolean requiresMatrixConvolution() {
return false;
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
// TODO Auto-generated method stub
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index,
ChangeType type) {
// TODO Auto-generated method stub
}
@Override
protected void storeState() {
// TODO Auto-generated method stub
}
@Override
protected void restoreState() {
// TODO Auto-generated method stub
}
@Override
protected void acceptState() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
try {
// the seed of the BEAST
MathUtils.setSeed(666);
// create tree
NewickImporter importer = new NewickImporter(
"(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
TreeModel tree = new TreeModel(importer.importTree(null));
// create site model
GammaSiteRateModel siteRateModel = new GammaSiteRateModel(
"siteModel");
// create branch rate model
BranchRateModel branchRateModel = new DefaultBranchRateModel();
int sequenceLength = 10;
ArrayList<Partition> partitionsList = new ArrayList<Partition>();
// create Frequency Model
Parameter freqs = new Parameter.Default(new double[]{
0.0163936,
0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344
});
FrequencyModel freqModel = new FrequencyModel(Codons.UNIVERSAL,
freqs);
// create substitution model
Parameter alpha = new Parameter.Default(1, 10);
Parameter beta = new Parameter.Default(1, 5);
MG94CodonModel mg94 = new MG94CodonModel(Codons.UNIVERSAL, alpha, beta, freqModel);
HomogeneousBranchModel substitutionModel = new HomogeneousBranchModel(mg94);
// create partition
Partition partition1 = new Partition(tree,
substitutionModel,
siteRateModel,
branchRateModel,
freqModel,
0, // from
sequenceLength - 1,
1 // every
);
partitionsList.add(partition1);
// feed to sequence simulator and generate data
BeagleSequenceSimulator simulator = new BeagleSequenceSimulator(
partitionsList);
Alignment alignment = simulator.simulate(false);
ConvertAlignment convert = new ConvertAlignment(Nucleotides.INSTANCE,
GeneticCode.UNIVERSAL, alignment);
List<SubstitutionModel> substModels = new ArrayList<SubstitutionModel>();
for (int i = 0; i < 2; i++) {
// alpha = new Parameter.Default(1, 10 );
// beta = new Parameter.Default(1, 5 );
// mg94 = new MG94CodonModel(Codons.UNIVERSAL, alpha, beta,
// freqModel);
substModels.add(mg94);
}
Parameter uCategories = new Parameter.Default(2);
CountableBranchCategoryProvider provider = new CountableBranchCategoryProvider.IndependentBranchCategoryModel(tree, uCategories);
BranchSpecific branchSpecific = new BranchSpecific(tree, substModels, provider, uCategories);
BeagleTreeLikelihood like = new BeagleTreeLikelihood(convert,
tree,
branchSpecific,
siteRateModel,
branchRateModel,
null,
false,
PartialsRescalingScheme.DEFAULT);
BeagleTreeLikelihood gold = new BeagleTreeLikelihood(convert,
tree,
substitutionModel,
siteRateModel,
branchRateModel,
null,
false,
PartialsRescalingScheme.DEFAULT);
System.out.println("likelihood (gold) = " + gold.getLogLikelihood());
System.out.println("likelihood = " + like.getLogLikelihood());
} catch (Exception e) {
e.printStackTrace();
}
}// END: main
}// END: class
|
package ch04q06_CommonAncestorOf2BinaryTreeNodes;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class BinaryTreeNode {
BinaryTreeNode left;
BinaryTreeNode right;
// path from this node to destination, in reverse order
// return null if no such path is found
public List<BinaryTreeNode> path(BinaryTreeNode destination) {
List<BinaryTreeNode> p = null;
if (this.equals(destination)) {
p = new LinkedList<BinaryTreeNode>();
p.add(this);
return p;
}
if (this.left != null) {
p = this.left.path(destination);
if (p != null) {
p.add(this);
return p;
}
}
if (this.right != null) {
p = this.right.path(destination);
if (p != null) {
p.add(this);
return p;
}
}
return null;
}
private static BinaryTreeNode firstCommon(List<BinaryTreeNode> path1, List<BinaryTreeNode> path2, int diff) {
ListIterator<BinaryTreeNode> itr1 = path1.listIterator();
// number of nodes to skip in longer path: diff
for (int i=0; i < diff; ++i) {
itr1.next();
}
ListIterator<BinaryTreeNode> itr2 = path2.listIterator();
while (itr1.hasNext() && itr2.hasNext()) {
BinaryTreeNode next1 = itr1.next();
BinaryTreeNode next2 = itr2.next();
if (next1.equals(next2)) {
return next1;
}
}
return null;
}
public BinaryTreeNode firstCommonAncestor1(BinaryTreeNode p, BinaryTreeNode q) {
List<BinaryTreeNode> path1 = this.path(p);
List<BinaryTreeNode> path2 = this.path(q);
if (path1 == null || path2 == null) {
return null;
}
// at most O(log n)
int diff = path2.size() - path1.size();
if (diff < 0) { // path1 is longer than path1
return firstCommon(path1, path2, 0-diff);
}
return firstCommon(path2, path1, diff);
};
private static int nodesFound = 0;
private BinaryTreeNode firstCommonAncestorRecursive(BinaryTreeNode p, BinaryTreeNode q) {
if (this.equals(p) || this.equals(q)) {
if (++nodesFound == 2) {
return null;
}
}
if (this.left != null) {
BinaryTreeNode first = this.left.firstCommonAncestorRecursive(p, q);
if (first != null) {
return first;
}
}
if (nodesFound < 2 && this.right != null) {
BinaryTreeNode first = this.right.firstCommonAncestorRecursive(p, q);
if (first != null) {
return first;
}
}
if (nodesFound == 2) {
nodesFound = 0;
return this;
}
return null;
}
public BinaryTreeNode firstCommonAncestor2(BinaryTreeNode p, BinaryTreeNode q) {
nodesFound = 0;
return this.firstCommonAncestorRecursive(p, q);
}
private static class FinderOfFirstCommonAncestor {
private int nodesFound = 0;
public BinaryTreeNode find(BinaryTreeNode root, BinaryTreeNode p, BinaryTreeNode q) {
if (root.equals(p) || root.equals(q)) {
if (++nodesFound == 2) {
return null;
}
}
BinaryTreeNode first = null;
if (root.left != null) {
first = this.find(root.left, p, q);
if (first != null) {
return first;
}
}
if (nodesFound < 2 && root.right != null) {
first = this.find(root.right, p, q);
if (first != null) {
return first;
}
}
if (nodesFound == 2) {
nodesFound = 0;
return root;
}
return null;
}
}
public BinaryTreeNode firstCommonAncestor2a(BinaryTreeNode p, BinaryTreeNode q) {
FinderOfFirstCommonAncestor finder = new FinderOfFirstCommonAncestor();
return finder.find(this, p, q);
}
public static void main(String[] args) {
// ideas for test cases; p & q are interchangable
// solution assumes binary tree is not corrupted -> no cycles, no node has > 2 children, etc.
// normal: p & q on different sides of a binary tree
// p & q are siblings of each other
// p & q are at different levels/height/depths
// p is parent of q
// p is ancestor of q
// either or both p & q are leaf nodes
// p is not in the tree -> null
// both p & q are not in the tree -> null
// binary tree has only root node
// ... etc.
}
}
|
package com.byclosure.jenkins.plugins.gcloud;
import com.cloudbees.jenkins.plugins.gcloudsdk.GCloudInstallation;
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.google.jenkins.plugins.credentials.domains.RequiresDomain;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentials;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.security.ACL;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.util.ListBoxModel;
import jenkins.tasks.SimpleBuildWrapper;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.annotation.CheckForNull;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;
@RequiresDomain(value = GCloudScopeRequirement.class)
public class GCloudBuildWrapper extends SimpleBuildWrapper {
private static final Logger LOGGER = Logger.getLogger(GCloudBuildWrapper.class.getName());
private final String installation;
private final String credentialsId;
@DataBoundConstructor
public GCloudBuildWrapper(String installation, String credentialsId) {
this.installation = installation;
this.credentialsId = credentialsId;
}
@Override
public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
GCloudInstallation sdk = getSDK();
if (sdk == null) {
throw new RuntimeException("Could not find a matching Google Cloud SDK installation: " + installation);
}
sdk = sdk.translate(workspace.toComputer().getNode(), initialEnvironment, listener);
final FilePath configDir = workspace.createTempDir("gcloud", "config");
final GCloudServiceAccount serviceAccount =
GCloudServiceAccount.getServiceAccount(build, launcher, listener, credentialsId, configDir);
if (!serviceAccount.activate(sdk)) {
configDir.deleteRecursive();
throw new InterruptedException("Couldn't activate GCloudServiceAccount");
}
sdk.buildEnvVars(initialEnvironment);
for (Map.Entry<String, String> entry : initialEnvironment.entrySet()) {
context.env(entry.getKey(), entry.getValue());
}
context.env("CLOUDSDK_CONFIG", configDir.getRemote());
context.env("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getKeyFile().getRemote());
context.setDisposer(new GCloudConfigDisposer(configDir));
}
public @CheckForNull GCloudInstallation getSDK() {
GCloudInstallation[] installations = GCloudInstallation.getInstallations();
if (installation.isEmpty() && installations.length > 0) {
return installations[0];
}
for (GCloudInstallation sdk : installations) {
if (installation.equals(sdk.getName())) return sdk;
}
return null;
}
public String getInstallation() {
return installation;
}
public String getCredentialsId() {
return credentialsId;
}
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
public DescriptorImpl() {
load();
}
@Override
public String getDisplayName() {
return "GCloud SDK authentication";
}
@Override
public boolean isApplicable(AbstractProject item) {
return true;
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
save();
return super.configure(req, formData);
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project,
@QueryParameter String serverAddress) {
if (project == null || !project.hasPermission(Item.CONFIGURE)) {
return new StandardListBoxModel();
}
return new StandardListBoxModel()
.withEmptySelection()
.withMatching(
MATCHER,
CredentialsProvider.lookupCredentials(GoogleRobotPrivateKeyCredentials.class,
project,
ACL.SYSTEM,
URIRequirementBuilder.fromUri(serverAddress).build()));
}
public static final CredentialsMatcher MATCHER = CredentialsMatchers.anyOf(CredentialsMatchers.instanceOf(GoogleRobotPrivateKeyCredentials.class));
}
private static class GCloudConfigDisposer extends Disposer {
private static final long serialVersionUID = 5723296082223871496L;
private final FilePath configDir;
public GCloudConfigDisposer(FilePath configDir) {
this.configDir = configDir;
}
@Override
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
configDir.deleteRecursive();
}
}
}
|
package com.creativemd.littletiles.common.item;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.lwjgl.util.Color;
import com.creativemd.creativecore.client.rendering.RenderCubeObject;
import com.creativemd.creativecore.client.rendering.model.CreativeBakedModel;
import com.creativemd.creativecore.client.rendering.model.ICreativeRendered;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiButton;
import com.creativemd.creativecore.common.packet.PacketHandler;
import com.creativemd.creativecore.common.utils.math.Rotation;
import com.creativemd.creativecore.common.utils.mc.ColorUtils;
import com.creativemd.creativecore.common.utils.tooltip.TooltipUtils;
import com.creativemd.littletiles.LittleTiles;
import com.creativemd.littletiles.client.gui.SubGuiChisel;
import com.creativemd.littletiles.client.gui.SubGuiMarkMode;
import com.creativemd.littletiles.client.gui.configure.SubGuiConfigure;
import com.creativemd.littletiles.client.gui.configure.SubGuiModeSelector;
import com.creativemd.littletiles.client.render.overlay.PreviewRenderer;
import com.creativemd.littletiles.common.action.LittleAction;
import com.creativemd.littletiles.common.api.ILittleTile;
import com.creativemd.littletiles.common.block.BlockTile;
import com.creativemd.littletiles.common.container.SubContainerConfigure;
import com.creativemd.littletiles.common.packet.LittleBlockPacket;
import com.creativemd.littletiles.common.packet.LittleBlockPacket.BlockPacketAction;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket.VanillaBlockAction;
import com.creativemd.littletiles.common.tile.LittleTile;
import com.creativemd.littletiles.common.tile.LittleTileColored;
import com.creativemd.littletiles.common.tile.math.box.LittleBox;
import com.creativemd.littletiles.common.tile.math.box.LittleBoxes;
import com.creativemd.littletiles.common.tile.math.vec.LittleAbsoluteVec;
import com.creativemd.littletiles.common.tile.preview.LittleAbsolutePreviews;
import com.creativemd.littletiles.common.tile.preview.LittlePreview;
import com.creativemd.littletiles.common.tile.preview.LittlePreviews;
import com.creativemd.littletiles.common.tile.registry.LittleTileRegistry;
import com.creativemd.littletiles.common.util.grid.LittleGridContext;
import com.creativemd.littletiles.common.util.place.MarkMode;
import com.creativemd.littletiles.common.util.place.PlacementMode;
import com.creativemd.littletiles.common.util.place.PlacementPosition;
import com.creativemd.littletiles.common.util.shape.DragShape;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.EnumFacing.AxisDirection;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemLittleChisel extends Item implements ICreativeRendered, ILittleTile {
public ItemLittleChisel() {
setCreativeTab(LittleTiles.littleTab);
hasSubtypes = true;
setMaxStackSize(1);
}
@Override
public float getDestroySpeed(ItemStack stack, IBlockState state) {
return 0F;
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
DragShape shape = getShape(stack);
tooltip.add("shape: " + shape.key);
shape.addExtraInformation(stack.getTagCompound(), tooltip);
LittlePreview preview = ItemLittleGrabber.SimpleMode.getPreview(stack);
tooltip.add(TooltipUtils.printRGB(preview.hasColor() ? preview.getColor() : ColorUtils.WHITE));
}
public static PlacementPosition min;
@SideOnly(Side.CLIENT)
public static PlacementPosition lastMax;
@Override
public boolean canDestroyBlockInCreative(World world, BlockPos pos, ItemStack stack, EntityPlayer player) {
return false;
}
public static DragShape getShape(ItemStack stack) {
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
return DragShape.getShape(stack.getTagCompound().getString("shape"));
}
public static void setShape(ItemStack stack, DragShape shape) {
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setString("shape", shape.key);
}
public static LittlePreview getPreview(ItemStack stack) {
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
if (stack.getTagCompound().hasKey("preview"))
return LittleTileRegistry.loadPreview(stack.getTagCompound().getCompoundTag("preview"));
IBlockState state = stack.getTagCompound().hasKey("state") ? Block.getStateById(stack.getTagCompound().getInteger("state")) : Blocks.STONE.getDefaultState();
LittleTile tile = stack.getTagCompound().hasKey("color") ? new LittleTileColored(state.getBlock(), state.getBlock().getMetaFromState(state), stack.getTagCompound().getInteger("color")) : new LittleTile(state.getBlock(), state.getBlock().getMetaFromState(state));
LittleGridContext context = LittleGridContext.get();
tile.box = new LittleBox(0, 0, 0, context.size, context.size, context.size);
LittlePreview preview = tile.getPreviewTile();
setPreview(stack, preview);
return preview;
}
public static void setPreview(ItemStack stack, LittlePreview preview) {
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
NBTTagCompound nbt = new NBTTagCompound();
preview.writeToNBT(nbt);
stack.getTagCompound().setTag("preview", nbt);
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(IBlockState state, TileEntity te, ItemStack stack) {
return Collections.emptyList();
}
@SideOnly(Side.CLIENT)
public static IBakedModel model;
@Override
@SideOnly(Side.CLIENT)
public void applyCustomOpenGLHackery(ItemStack stack, TransformType cameraTransformType) {
Minecraft mc = Minecraft.getMinecraft();
GlStateManager.pushMatrix();
if (model == null)
model = mc.getRenderItem().getItemModelMesher().getModelManager().getModel(new ModelResourceLocation(LittleTiles.modid + ":chisel_background", "inventory"));
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
mc.getRenderItem().renderItem(new ItemStack(Items.PAPER), model);
if (cameraTransformType == TransformType.GUI) {
GlStateManager.translate(0.1, 0.1, 0);
GlStateManager.scale(0.7, 0.7, 0.7);
LittlePreview preview = getPreview(stack);
ItemStack blockStack = new ItemStack(preview.getBlock(), 1, preview.getMeta());
IBakedModel model = mc.getRenderItem().getItemModelWithOverrides(blockStack, mc.world, mc.player); // getItemModelMesher().getItemModel(blockStack);
if (!(model instanceof CreativeBakedModel))
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
GlStateManager.disableDepth();
GlStateManager.pushMatrix();
GlStateManager.translate(-0.5F, -0.5F, -0.5F);
try {
if (model.isBuiltInRenderer()) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableRescaleNormal();
TileEntityItemStackRenderer.instance.renderByItem(blockStack);
} else {
Color color = preview.hasColor() ? ColorUtils.IntToRGBA(preview.getColor()) : ColorUtils.IntToRGBA(ColorUtils.WHITE);
color.setAlpha(255);
ReflectionHelper.findMethod(RenderItem.class, "renderModel", "func_191967_a", IBakedModel.class, int.class, ItemStack.class).invoke(mc.getRenderItem(), model, preview.hasColor() ? ColorUtils.RGBAToInt(color) : -1, blockStack);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
GlStateManager.popMatrix();
GlStateManager.enableDepth();
}
GlStateManager.popMatrix();
}
@Override
public boolean hasLittlePreview(ItemStack stack) {
return true;
}
private static LittleAbsoluteVec cachedPos;
private static LittleBoxes cachedShape;
private static boolean cachedLow;
private static NBTTagCompound cachedSettings;
@SideOnly(Side.CLIENT)
private static EntityPlayer getPlayer() {
return Minecraft.getMinecraft().player;
}
@Override
public LittleAbsolutePreviews getLittlePreview(ItemStack stack) {
return null;
}
@Override
public LittleAbsolutePreviews getLittlePreview(ItemStack stack, boolean allowLowResolution, boolean marked) {
PlacementPosition min = ItemLittleChisel.min;
if (min == null)
min = lastMax;
if (min != null) {
if (lastMax == null)
lastMax = min.copy();
min.forceContext(lastMax);
LittleGridContext context = getPositionContext(stack);
if (context.size < min.getContext().size)
context = min.getContext();
LittleAbsoluteVec offset = new LittleAbsoluteVec(lastMax.getPos(), context);
if (lastMax == null)
lastMax = min.copy();
LittleBoxes boxes = null;
if (cachedPos == null || !cachedPos.equals(lastMax) || !cachedSettings.equals(stack.getTagCompound()) || cachedLow != allowLowResolution) {
DragShape shape = getShape(stack);
LittleBox newBox = new LittleBox(new LittleBox(min.getRelative(offset).getVec(context)), new LittleBox(lastMax.getRelative(offset).getVec(context)));
boxes = shape.getBoxes(new LittleBoxes(offset.getPos(), context), newBox.getMinVec(), newBox.getMaxVec(), getPlayer(), stack.getTagCompound(), allowLowResolution, min, lastMax);
cachedPos = lastMax.copy();
cachedShape = boxes.copy();
cachedSettings = stack.getTagCompound().copy();
cachedLow = allowLowResolution;
} else
boxes = cachedShape;
LittleAbsolutePreviews previews = new LittleAbsolutePreviews(offset.getPos(), boxes.context);
LittlePreview preview = getPreview(stack);
for (int i = 0; i < boxes.size(); i++) {
LittlePreview newPreview = preview.copy();
newPreview.box = boxes.get(i);
previews.addWithoutCheckingPreview(newPreview);
}
return previews;
}
return null;
}
@Override
public void saveLittlePreview(ItemStack stack, LittlePreviews previews) {}
@Override
public void rotateLittlePreview(EntityPlayer player, ItemStack stack, Rotation rotation) {
getShape(stack).rotate(stack.getTagCompound(), rotation);
}
@Override
public void flipLittlePreview(EntityPlayer player, ItemStack stack, Axis axis) {
getShape(stack).flip(stack.getTagCompound(), axis);
}
@Override
@SideOnly(Side.CLIENT)
public float getPreviewAlphaFactor() {
return 0.4F;
}
@Override
@SideOnly(Side.CLIENT)
public void tickPreview(EntityPlayer player, ItemStack stack, PlacementPosition position, RayTraceResult result) {
lastMax = getPosition(position, result, currentMode);
}
@Override
@SideOnly(Side.CLIENT)
public boolean shouldCache() {
return false;
}
@Override
public void onDeselect(EntityPlayer player, ItemStack stack) {
min = null;
lastMax = null;
}
protected static PlacementPosition getPosition(PlacementPosition position, RayTraceResult result, PlacementMode mode) {
position = position.copy();
EnumFacing facing = position.facing;
if (mode.placeInside)
facing = facing.getOpposite();
if (facing.getAxisDirection() == AxisDirection.NEGATIVE)
position.getVec().add(facing);
return position;
}
@Override
public boolean onRightClick(World world, EntityPlayer player, ItemStack stack, PlacementPosition position, RayTraceResult result) {
if (ItemLittleChisel.min == null) {
ItemLittleChisel.min = getPosition(position, result, currentMode);
} else if (LittleAction.isUsingSecondMode(player)) {
ItemLittleChisel.min = null;
ItemLittleChisel.lastMax = null;
ItemLittleChisel.cachedPos = null;
ItemLittleChisel.cachedSettings = null;
ItemLittleChisel.cachedShape = null;
PreviewRenderer.marked = null;
} else
return true;
return false;
}
@Override
@SideOnly(Side.CLIENT)
public boolean onMouseWheelClickBlock(World world, EntityPlayer player, ItemStack stack, RayTraceResult result) {
IBlockState state = world.getBlockState(result.getBlockPos());
if (LittleAction.isBlockValid(state)) {
PacketHandler.sendPacketToServer(new LittleVanillaBlockPacket(result.getBlockPos(), VanillaBlockAction.CHISEL));
return true;
} else if (state.getBlock() instanceof BlockTile) {
PacketHandler.sendPacketToServer(new LittleBlockPacket(world, result.getBlockPos(), player, BlockPacketAction.CHISEL, new NBTTagCompound()));
return true;
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiConfigure getConfigureGUI(EntityPlayer player, ItemStack stack) {
return new SubGuiChisel(stack);
}
@Override
public SubContainerConfigure getConfigureContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerConfigure(player, stack);
}
public static PlacementMode currentMode = PlacementMode.fill;
@Override
public PlacementMode getPlacementMode(ItemStack stack) {
return currentMode;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiConfigure getConfigureGUIAdvanced(EntityPlayer player, ItemStack stack) {
return new SubGuiModeSelector(stack, ItemMultiTiles.currentContext, currentMode) {
@Override
public void saveConfiguration(LittleGridContext context, PlacementMode mode) {
currentMode = mode;
ItemMultiTiles.currentContext = context;
}
};
}
@Override
@SideOnly(Side.CLIENT)
public MarkMode onMark(EntityPlayer player, ItemStack stack) {
if (min == null)
if (lastMax != null)
min = lastMax.copy();
else
return null;
return new MarkMode() {
@Override
public SubGui getConfigurationGui() {
return new SubGuiMarkMode(this) {
@Override
public void createControls() {
super.createControls();
controls.add(new GuiButton(I18n.translateToLocal("markmode.gui.switchpos"), 10, 20) {
@Override
public void onClicked(int x, int y, int button) {
if (lastMax == null)
lastMax = min.copy();
mode.position = min;
min = lastMax;
lastMax = mode.position;
}
});
}
};
}
};
}
@Override
public boolean containsIngredients(ItemStack stack) {
return false;
}
@Override
public LittleGridContext getPositionContext(ItemStack stack) {
return ItemMultiTiles.currentContext;
}
}
|
package com.demonwav.mcdev.platform.bungeecord;
import com.demonwav.mcdev.asset.PlatformAssets;
import com.demonwav.mcdev.buildsystem.BuildSystem;
import com.demonwav.mcdev.buildsystem.SourceType;
import com.demonwav.mcdev.platform.AbstractModule;
import com.demonwav.mcdev.platform.MinecraftModuleType;
import com.demonwav.mcdev.platform.PlatformType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import javax.swing.Icon;
import java.util.HashMap;
import java.util.Map;
public class BungeeCordModule extends AbstractModule {
private static final Map<Module, BungeeCordModule> map = new HashMap<>();
private VirtualFile pluginYml;
private BungeeCordModule(@NotNull Module module) {
this.module = module;
buildSystem = BuildSystem.getInstance(module);
if (buildSystem != null) {
buildSystem.reImport(module, PlatformType.BUNGEECORD);
pluginYml = buildSystem.findFile("plugin.yml", SourceType.RESOURCE);
}
}
@NotNull
public Module getModule() {
return module;
}
@Override
public MinecraftModuleType getModuleType() {
return BungeeCordModuleType.getInstance();
}
public VirtualFile getPluginYml() {
if (pluginYml == null && buildSystem != null) {
// try and find the file again if it's not already present
// when this object was first created it may not have been ready
pluginYml = buildSystem.findFile("plugin.yml", SourceType.RESOURCE);
}
return pluginYml;
}
public void setPluginYml(VirtualFile pluginYml) {
this.pluginYml = pluginYml;
}
@Override
public PlatformType getType() {
return PlatformType.BUNGEECORD;
}
@Override
public Icon getIcon() {
return PlatformAssets.BUNGEECORD_ICON;
}
}
|
package com.depas.functional.optional;
import java.util.Optional;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
public class OptionalPropertiesExample {
public static int readDurationImp(Properties props, String name) {
String value = props.getProperty(name);
if (value != null) {
try {
int intValue = Integer.parseInt(value);
if (intValue > 0) {
return intValue;
}
} catch (NumberFormatException nfe) {}
}
return 0;
}
public static int readDuration(Properties props, String name) {
return Optional.ofNullable(props.getProperty(name))
.flatMap(OptionalUtility::stringToInt)
.filter(i -> i > 0)
.orElse(0);
}
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("prop1", "5");
props.setProperty("prop2", "true");
props.setProperty("prop3", "-3");
props.setProperty("prop4", "1");
assertEquals(5, readDurationImp(props, "prop1"));
assertEquals(0, readDurationImp(props, "prop2"));
assertEquals(0, readDurationImp(props, "prop3"));
assertEquals(1, readDurationImp(props, "prop4"));
System.out.println("prop1: " + readDurationImp(props, "prop1"));
System.out.println("prop2: " + readDurationImp(props, "prop2"));
System.out.println("prop3: " + readDurationImp(props, "prop3"));
System.out.println("prop4: " + readDurationImp(props, "prop4"));
System.out.println("prop5: " + readDurationImp(props, "prop5"));
assertEquals(5, readDuration(props, "prop1"));
assertEquals(0, readDuration(props, "prop2"));
assertEquals(0, readDuration(props, "prop3"));
assertEquals(1, readDuration(props, "prop4"));
System.out.println("
System.out.println("prop1: " + readDuration(props, "prop1"));
System.out.println("prop2: " + readDuration(props, "prop2"));
System.out.println("prop3: " + readDuration(props, "prop3"));
System.out.println("prop4: " + readDuration(props, "prop4"));
System.out.println("prop5: " + readDuration(props, "prop5"));
}
}
|
package com.gmail.woodyc40.commons.reflection.asm;
import com.gmail.woodyc40.commons.reflection.asm.sun.ClassFileAssembler;
public class BytecodeField {
/**
* The access modifiers of the field, specified by {@link com.gmail.woodyc40.commons.reflection.asm.Modifiers}
*/
private final int access;
/**
* The declared title of the field
*/
private final String name;
/**
* The descriptor of the field, for internal use only. Can be used to decode <code>class</code> type of
* the field
*/
private final String desc;
/**
* Creates a new instnance of a field specifier.
*
* @param name the name of the field to be declared by the bytecode dump
* @param access the access modifiers of the field, specified by
* {@link com.gmail.woodyc40.commons.reflection.asm.Modifiers}
* @param type the type of field to be assigned a value, for example:
* <code>byte vec;</code> would be <code>byte.class</code>
*/
public BytecodeField(String name, int access, Class<?> type) {
this.access = access;
this.name = name;
this.desc = Descriptors.descField(type);
}
/**
* Adds the field to the bytecode dump of a represented builder
*
* @param bytecode the builder to add the field bytecode to
*/
public void add(ClassBytecode bytecode) {
ClassFileAssembler assembler = bytecode.getAssembler();
Pool pool = bytecode.getConstantPool();
assembler.emitShort((short) access); // Access
assembler.emitShort((short) pool.newUTF(name)); // Name
assembler.emitShort((short) pool.newUTF(desc)); // Descriptor
assembler.emitShort((short) 0); // Attributes // TODO attributes for code ? fields = value
}
}
|
package com.ickstream.protocol.cloud.content;
import com.ickstream.common.jsonrpc.HttpMessageSender;
import com.ickstream.common.jsonrpc.MessageLogger;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
public class HttpContentService extends ContentService {
public HttpContentService(String id, String endpoint) {
super(id, new HttpMessageSender(createHttpClient(), endpoint, true));
((HttpMessageSender) getMessageSender()).setResponseHandler(this);
}
public HttpContentService(String id, String endpoint, String accessToken) {
this(id, endpoint);
((HttpMessageSender) getMessageSender()).setAccessToken(accessToken);
}
public void setMessageLogger(MessageLogger messageLogger) {
((HttpMessageSender) getMessageSender()).setMessageLogger(messageLogger);
}
public void setAccessToken(String accessToken) {
((HttpMessageSender) getMessageSender()).setAccessToken(accessToken);
}
private static HttpClient createHttpClient() {
try {
Class.forName("org.apache.http.impl.conn.PoolingClientConnectionManager");
return new DefaultHttpClient(new PoolingClientConnectionManager());
} catch (ClassNotFoundException e) {
return new DefaultHttpClient(new ThreadSafeClientConnManager());
}
}
}
|
package com.imcode.imcms.components.impl;
import com.imcode.imcms.components.MenuElementHtmlWrapper;
import com.imcode.imcms.components.MenuHtmlConverter;
import com.imcode.imcms.domain.dto.MenuItemDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static com.imcode.imcms.components.MenuElementHtmlWrapper.*;
@Component
class ImcmsMenuHtmlConverter implements MenuHtmlConverter {
private final MenuElementHtmlWrapper menuElementHtmlWrapper;
ImcmsMenuHtmlConverter(MenuElementHtmlWrapper menuElementHtmlWrapper) {
this.menuElementHtmlWrapper = menuElementHtmlWrapper;
}
@Override
public String convertToMenuHtml(int docId, int menuIndex, List<MenuItemDTO> menuItemDTOS,
boolean nested, String attributes, String treeKey, String wrap) {
List<MenuItemDTO> menuItems;
final StringBuilder buildContentMenu = new StringBuilder();
final List<String> listAttr = StringUtils.isBlank(attributes)
? Collections.EMPTY_LIST
: Arrays.asList(attributes.split(","));
for (String attribute : listAttr) {
switch (attribute.trim()) {
case ATTRIBUTE_CLASS:
addStartBuildUlByClassAttr(buildContentMenu, menuIndex, docId);
break;
case ATTRIBUTE_DATA:
addStartBuildUlByDataAttr(buildContentMenu, menuIndex, docId);
break;
}
}
buildContentMenu.append(">");
boolean existDataAttribute = attributesHasData(attributes);
if (nested) {
menuItems = menuItemDTOS;
} else {
menuItems = menuItemDTOS.stream()
.flatMap(MenuItemDTO::flattened)
.collect(Collectors.toList());
}
List<String> wrappers = StringUtils.isBlank(wrap) ? Collections.EMPTY_LIST : Arrays.asList(wrap.split(","));
Collections.reverse(wrappers);
for (int i = 0; i < menuItems.size(); i++) {
final MenuItemDTO currentParentItem = menuItems.get(i);
String dataTreeKey = StringUtils.isBlank(treeKey) ? ((i + 1) * 10) + "" : treeKey + "." + ((i + 1) * 10);
buildContentMenu.append(getBuiltMainParentMenuItem(currentParentItem, attributes, dataTreeKey, 1, wrappers));
if (!currentParentItem.getChildren().isEmpty()) {
buildChildrenContentMenuItem(buildContentMenu.append(UL_TAG_OPEN), currentParentItem.getChildren(),
dataTreeKey, 2, wrappers, existDataAttribute);
buildContentMenu.append(UL_TAG_CLOSE).append(LI_TAG_CLOSE);
}
}
buildContentMenu.append(UL_TAG_CLOSE);//main ul tag closed
return buildContentMenu.toString();
}
@Override
public String convertToMenuHtml(int docId, int menuIndex) {
return null;
}
private boolean attributesHasData(String attributes) {
return attributes.contains("data");
}
private String getBuiltMainParentMenuItem(MenuItemDTO parentMenuItem, String attributes,
String treeKey, Integer dataLevel, List<String> wrappers) {
StringBuilder parentElementContent = new StringBuilder();
final boolean hasChildren = !parentMenuItem.getChildren().isEmpty();
String htmlContentItemElement;
if (attributesHasData(attributes)) {
htmlContentItemElement = String.format(
"<li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s",
DATA_META_ID_ATTRIBUTE, parentMenuItem.getDocumentId(),
DATA_INDEX_ATTRIBUTE, parentMenuItem.getDataIndex(),
DATA_TREEKEY_ATTRIBUTE, treeKey,
DATA_LEVEL_ATTRIBUTE, dataLevel,
DATA_SUBLEVELS_ATTRIBUTE, hasChildren,
parentMenuItem.getTitle());
final String wrappedContent = wrapElement(parentMenuItem, wrappers, htmlContentItemElement);
addWrapElementToParentContentHtml(parentElementContent, hasChildren, wrappedContent);
} else {
htmlContentItemElement = String.format("<li>%s", parentMenuItem.getTitle());
final String wrappedContent = wrapElement(parentMenuItem, wrappers, htmlContentItemElement);
addWrapElementToParentContentHtml(parentElementContent, hasChildren, wrappedContent);
}
return parentElementContent.toString();
}
private String wrapElement(MenuItemDTO parentItem, List<String> wrappers, String htmlContentItemElement) {
if (!wrappers.isEmpty()) {
return menuElementHtmlWrapper.getWrappedContent(htmlContentItemElement, wrappers, parentItem);
}
return htmlContentItemElement;
}
private void addWrapElementToParentContentHtml(StringBuilder parentElementContent,
boolean hasChildren, String wrappedElement) {
if (hasChildren) {
parentElementContent.append(wrappedElement);
} else {
parentElementContent.append(wrappedElement).append(LI_TAG_CLOSE);
}
}
private void buildChildrenContentMenuItem(StringBuilder contentMenu, List<MenuItemDTO> childrenItems,
String treeKey, Integer dataLvl, List<String> wrappers, boolean existDataAttr) {
for (int i = 0; i < childrenItems.size(); i++) {
final MenuItemDTO currentMenuItem = childrenItems.get(i);
if (!currentMenuItem.getChildren().isEmpty()) {
String htmlContentMenuItem = existDataAttr
? String.format(
"<li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s",
DATA_META_ID_ATTRIBUTE, currentMenuItem.getDocumentId(),
DATA_INDEX_ATTRIBUTE, currentMenuItem.getDataIndex(),
DATA_TREEKEY_ATTRIBUTE, treeKey + "." + ((i + 1) * 10),
DATA_LEVEL_ATTRIBUTE, dataLvl,
DATA_SUBLEVELS_ATTRIBUTE, !currentMenuItem.getChildren().isEmpty(),
currentMenuItem.getTitle())
: String.format("<li>%s", currentMenuItem.getTitle());
contentMenu.append(wrapElement(currentMenuItem, wrappers, htmlContentMenuItem));
buildChildrenContentMenuItem(contentMenu.append(UL_TAG_OPEN), currentMenuItem.getChildren(),
treeKey + "." + ((i + 1) * 10), dataLvl + 1, wrappers, existDataAttr);
} else {
contentMenu.append(getBuildContentMenuItem(currentMenuItem, dataLvl,
treeKey + "." + ((i + 1) * 10), wrappers, existDataAttr));
}
}
contentMenu.append(UL_TAG_CLOSE).append(LI_TAG_CLOSE);
}
private String getBuildContentMenuItem(MenuItemDTO itemDTO, Integer dataLvl,
String treeKey, List<String> wrappers, boolean existDataAttr) {
String contentMenuItem = existDataAttr
? String.format(
"<li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s</li>",
DATA_META_ID_ATTRIBUTE, itemDTO.getDocumentId(),
DATA_INDEX_ATTRIBUTE, itemDTO.getDataIndex(),
DATA_TREEKEY_ATTRIBUTE, treeKey,
DATA_LEVEL_ATTRIBUTE, dataLvl,
DATA_SUBLEVELS_ATTRIBUTE, !itemDTO.getChildren().isEmpty(),
itemDTO.getTitle()).concat("\n")
: String.format("<li>%s</li>", itemDTO.getTitle()).concat("\n");
contentMenuItem = wrapElement(itemDTO, wrappers, contentMenuItem);
return contentMenuItem;
}
private void addStartBuildUlByClassAttr(StringBuilder buildContentMenu, int menuIndex, int docId) {
if (buildContentMenu.toString().isEmpty()) {
buildContentMenu.append(String.format("<ul class=\"%s %s %s %s
IMCMS_MENU_CLASS, IMCMS_MENU_BRANCH,
LVL_ELEMENT + 1, IMCMS_MENU_CLASS,
menuIndex, docId));
} else {
buildContentMenu.append(String.format(" class=\"%s %s %s %s
IMCMS_MENU_CLASS, IMCMS_MENU_BRANCH,
LVL_ELEMENT + 1, IMCMS_MENU_CLASS,
menuIndex, docId));
}
}
private void addStartBuildUlByDataAttr(StringBuilder buildContentMenu, int menuIndex, int docId) {
if (buildContentMenu.toString().isEmpty()) {
buildContentMenu.append(String.format("<ul class=\"%s %s %s %s
IMCMS_MENU_CLASS, IMCMS_MENU_BRANCH,
LVL_ELEMENT + 1, IMCMS_MENU_CLASS,
menuIndex, docId));
} else {
buildContentMenu.append(String.format(" class=\"%s %s %s %s
IMCMS_MENU_CLASS, IMCMS_MENU_BRANCH,
LVL_ELEMENT + 1, IMCMS_MENU_CLASS,
menuIndex, docId));
}
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.ImageDTO;
import com.imcode.imcms.domain.dto.LoopEntryRefDTO;
import com.imcode.imcms.domain.factory.ImageInTextFactory;
import com.imcode.imcms.domain.service.AbstractVersionedContentService;
import com.imcode.imcms.domain.service.ImageHistoryService;
import com.imcode.imcms.domain.service.ImageService;
import com.imcode.imcms.domain.service.LanguageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.model.LoopEntryRef;
import com.imcode.imcms.persistence.entity.Image;
import com.imcode.imcms.persistence.entity.LanguageJPA;
import com.imcode.imcms.persistence.entity.LoopEntryRefJPA;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.ImageRepository;
import com.imcode.imcms.util.function.TernaryFunction;
import imcode.util.ImcmsImageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
@Transactional
@Service("imageService")
class DefaultImageService extends AbstractVersionedContentService<Image, ImageRepository> implements ImageService {
private final VersionService versionService;
private final LanguageService languageService;
private final ImageHistoryService imageHistoryService;
private final TernaryFunction<ImageDTO, Version, Language, Image> imageDtoToImage;
private final ImageInTextFactory imageInTextFactory;
private final Function<Image, ImageDTO> imageToImageDTO;
DefaultImageService(ImageRepository imageRepository,
VersionService versionService,
LanguageService languageService,
ImageHistoryService imageHistoryService, TernaryFunction<ImageDTO, Version, Language, Image> imageDtoToImage,
ImageInTextFactory imageInTextFactory,
Function<Image, ImageDTO> imageToImageDTO) {
super(imageRepository);
this.versionService = versionService;
this.languageService = languageService;
this.imageHistoryService = imageHistoryService;
this.imageDtoToImage = imageDtoToImage;
this.imageInTextFactory = imageInTextFactory;
this.imageToImageDTO = imageToImageDTO;
}
@Override
public ImageDTO getImage(ImageDTO dataHolder) {
if ((dataHolder.getIndex() == null) && dataHolder.isInText()) {
return imageInTextFactory.createWithIndex(dataHolder);
}
return getImage(
dataHolder.getDocId(),
dataHolder.getIndex(),
dataHolder.getLangCode(),
dataHolder.getLoopEntryRef()
);
}
@Override
public ImageDTO getImage(int docId, int index, String langCode, LoopEntryRef loopEntryRef) {
return getImage(docId, index, langCode, loopEntryRef, versionService::getDocumentWorkingVersion);
}
@Override
public ImageDTO getPublicImage(int docId, int index, String langCode, LoopEntryRef loopEntryRef) {
return getImage(docId, index, langCode, loopEntryRef, versionService::getLatestVersion);
}
@Override
public List<Image> getUsedImagesInWorkingAndLatestVersions(String imageURL) {
List<Image> plainImageFound = repository.findByUrl(imageURL);
Map<Integer, Optional<Integer>> imageMaxVersions = plainImageFound.stream()
.map(Image::getVersion)
.filter(image -> image.getNo() > 0)
.collect(groupingBy(Version::getDocId,
mapping(Version::getNo, maxBy(Integer::compare))));
List<Integer> latestDocIds = imageMaxVersions.keySet().stream()
.filter(docId -> versionService.getLatestVersion(docId).getNo() == imageMaxVersions.get(docId).get())
.collect(toList());
imageMaxVersions.keySet().retainAll(latestDocIds);
return plainImageFound.stream()
.filter(image -> {
@NotNull final Version version = image.getVersion();
return version.getNo() == 0
|| version.getNo() == (imageMaxVersions.getOrDefault(version.getDocId(), Optional.of(0)).get());
})
.collect(Collectors.toList());
}
@Override
public Set<Image> getImagesAllVersionAndLanguages(int docId, Language language) {
final Version version = versionService.getLatestVersion(docId);
return repository.findByVersionAndLanguage(version, new LanguageJPA(language));
}
@Override
public void saveImage(ImageDTO imageDTO) {
final Integer docId = imageDTO.getDocId();
final Version version = versionService.getDocumentWorkingVersion(docId);
generateImage(imageDTO);
if (imageDTO.isAllLanguages()) {
languageService.getAll().forEach(language -> saveImage(imageDTO, new LanguageJPA(language), version));
} else {
final LanguageJPA language = new LanguageJPA(languageService.findByCode(imageDTO.getLangCode()));
saveImage(imageDTO, language, version);
updateImagesWithDifferentLangCode(imageDTO, version);
}
super.updateWorkingVersion(docId);
}
@Override
public void deleteByDocId(Integer docIdToDelete) {
repository.deleteByDocId(docIdToDelete);
}
@Override
public Set<String> getPublicImageLinks(int docId, Language language) {
final Version latestVersion = versionService.getLatestVersion(docId);
return repository.findNonEmptyImageLinkUrlByVersionAndLanguage(latestVersion, new LanguageJPA(language));
}
@Override
public void regenerateImages() { // If generated images was cleared before start up
repository.findAllRegenerationCandidates()
.forEach((img) -> {
final ImageDTO imageDTO = imageToImageDTO.apply(img);
imageDTO.setSource(ImcmsImageUtils.getImageSource(imageDTO.getPath()));
if (StringUtils.isBlank(imageDTO.getGeneratedFilename())) {
final String generatedFilename = ImcmsImageUtils.generateImageFileName(imageDTO);
imageDTO.setGeneratedFilename(generatedFilename);
img.setGeneratedFilename(generatedFilename);
repository.save(img);
}
ImcmsImageUtils.generateImage(imageDTO, false);
});
}
@Override
public void deleteImage(ImageDTO imageDTO) {
final Integer docId = imageDTO.getDocId();
final Version version = versionService.getDocumentWorkingVersion(docId);
final LanguageJPA language = new LanguageJPA(languageService.findByCode(imageDTO.getLangCode()));
final Integer imageId = getImageId(imageDTO, version, language);
if (imageId != null) {
if (imageDTO.isAllLanguages()) {
final LoopEntryRefDTO loopEntryRef = imageDTO.getLoopEntryRef();
final Integer index = imageDTO.getIndex();
languageService.getAll()
.stream()
.map(LanguageJPA::new)
.forEach(languageJPA -> {
final Image image = getImage(index, version, languageJPA, loopEntryRef);
repository.delete(image);
});
} else {
final Image image = imageDtoToImage.apply(imageDTO, version, language);
image.setId(imageId);
repository.delete(image);
updateImagesWithDifferentLangCode(imageDTO, version);
}
super.updateWorkingVersion(docId);
}
}
private void updateImagesWithDifferentLangCode(ImageDTO imageDTO, Version version) {
languageService.getAll().forEach(language -> {
final LanguageJPA languageJPA = new LanguageJPA(language);
final Image image = getImage(imageDTO.getIndex(), version, languageJPA, imageDTO.getLoopEntryRef());
if (image != null) {
image.setAllLanguages(false);
repository.save(image);
}
});
}
private ImageDTO getImage(int docId, int index, String langCode, LoopEntryRef loopEntryRef,
Function<Integer, Version> versionReceiver) {
final Version version = versionReceiver.apply(docId);
final LanguageJPA language = new LanguageJPA(languageService.findByCode(langCode));
final Image image = getImage(index, version, language, loopEntryRef);
return Optional.ofNullable(image)
.map(imageToImageDTO)
.orElse(new ImageDTO(index, docId, loopEntryRef, langCode));
}
private void generateImage(ImageDTO imageDTO) {
String imagePath = imageDTO.getPath();
if (StringUtils.isNotBlank(imagePath)) {
imageDTO.setSource(ImcmsImageUtils.getImageSource(imagePath));
imageDTO.setGeneratedFilename(ImcmsImageUtils.generateImageFileName(imageDTO));
ImcmsImageUtils.generateImage(imageDTO, true);
}
}
private Image getImage(int index, Version version, LanguageJPA language, LoopEntryRef loopEntryRef) {
if (loopEntryRef == null) {
return repository.findByVersionAndLanguageAndIndexWhereLoopEntryRefIsNull(version, language, index);
} else {
return repository.findByVersionAndLanguageAndIndexAndLoopEntryRef(
version, language, index, new LoopEntryRefJPA(loopEntryRef)
);
}
}
private Integer getImageId(ImageDTO imageDTO, Version version, LanguageJPA language) {
final Integer index = imageDTO.getIndex();
final LoopEntryRef loopEntryRefDTO = imageDTO.getLoopEntryRef();
final Image image = getImage(index, version, language, loopEntryRefDTO);
if (image == null) {
return null;
}
return image.getId();
}
private void saveImage(ImageDTO imageDTO, LanguageJPA language, Version version) {
final Image image = imageDtoToImage.apply(imageDTO, version, language);
final Integer imageId = getImageId(imageDTO, version, language);
image.setId(imageId);
repository.save(image);
imageHistoryService.save(image);
}
@Override
protected Image removeId(Image image, Version version) {
return new Image(image, version);
}
}
|
package com.jaquadro.minecraft.storagedrawers.integration;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.storage.EmptyDrawerAttributes;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerAttributes;
import com.jaquadro.minecraft.storagedrawers.api.storage.IFractionalDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.attribute.LockAttribute;
import com.jaquadro.minecraft.storagedrawers.block.BlockDrawers;
import com.jaquadro.minecraft.storagedrawers.block.tile.TileEntityDrawers;
import com.jaquadro.minecraft.storagedrawers.capabilities.CapabilityDrawerAttributes;
import com.jaquadro.minecraft.storagedrawers.config.CommonConfig;
import mcp.mobius.waila.api.*;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.IFormattableTextComponent;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import javax.annotation.Nonnull;
import java.util.List;
@WailaPlugin(StorageDrawers.MOD_ID)
public class Waila implements IWailaPlugin
{
@Override
public void register (IRegistrar registrar) {
registerProvider(registrar);
}
private void registerProvider(IRegistrar registrar) {
WailaDrawer provider = new WailaDrawer();
registrar.addConfig(new ResourceLocation(StorageDrawers.MOD_ID, "display.content"), true);
registrar.addConfig(new ResourceLocation(StorageDrawers.MOD_ID, "display.stacklimit"), true);
registrar.addConfig(new ResourceLocation(StorageDrawers.MOD_ID, "display.status"), true);
registrar.registerComponentProvider(provider, TooltipPosition.BODY, BlockDrawers.class);
}
public static class WailaDrawer implements IComponentProvider
{
@Override
@Nonnull
public ItemStack getStack (IDataAccessor accessor, IPluginConfig config) {
return new ItemStack(accessor.getBlock(), 1);
}
@Override
public void appendBody (List<ITextComponent> currenttip, IDataAccessor accessor, IPluginConfig config) {
TileEntityDrawers tile = (TileEntityDrawers) accessor.getTileEntity();
IDrawerAttributes attr = tile.getCapability(CapabilityDrawerAttributes.DRAWER_ATTRIBUTES_CAPABILITY, null).orElse(EmptyDrawerAttributes.EMPTY);
//if (SecurityManager.hasAccess(Minecraft.getInstance().player.getGameProfile(), tile)) {
if (config.get(new ResourceLocation(StorageDrawers.MOD_ID, "display.content"))) {
for (int i = 0; i < tile.getDrawerCount(); i++) {
IDrawer drawer = tile.getDrawer(i);
if (!drawer.isEnabled())
continue;
ITextComponent name = new TranslationTextComponent("tooltip.storagedrawers.waila.empty");
ItemStack stack = drawer.getStoredItemPrototype();
if (!stack.isEmpty()) {
IFormattableTextComponent stackName = new StringTextComponent("").append(stack.getHoverName());
if (drawer.getStoredItemCount() == Integer.MAX_VALUE) {
name = stackName.append("[\u221E]");
}
else if (drawer instanceof IFractionalDrawer && ((IFractionalDrawer) drawer).getConversionRate() > 1) {
String text = ((i == 0) ? " [" : " [+") + ((IFractionalDrawer) drawer).getStoredItemRemainder() + "]";
name = stackName.append(text);
}
else if (CommonConfig.INTEGRATION.wailaStackRemainder.get()) {
int stacks = drawer.getStoredItemCount() / drawer.getStoredItemStackSize();
int remainder = drawer.getStoredItemCount() - (stacks * drawer.getStoredItemStackSize());
if (stacks > 0 && remainder > 0)
name = stackName.append(" [" + stacks + "x" + drawer.getStoredItemStackSize() + " + " + remainder + "]");
else if (stacks > 0)
name = stackName.append(" [" + stacks + "x" + drawer.getStoredItemStackSize() + "]");
else
name = stackName.append(" [" + remainder + "]");
} else
name = stackName.append(" [" + drawer.getStoredItemCount() + "]");
}
currenttip.add(new TranslationTextComponent("tooltip.storagedrawers.waila.drawer", i + 1, name));
}
}
if (config.get(new ResourceLocation(StorageDrawers.MOD_ID, "display.stacklimit"))) {
if (tile.getDrawerAttributes().isUnlimitedStorage() || tile.getDrawerAttributes().isUnlimitedVending())
currenttip.add(new TranslationTextComponent("tooltip.storagedrawers.waila.nolimit"));
else {
int multiplier = tile.upgrades().getStorageMultiplier();
int limit = tile.getEffectiveDrawerCapacity() * multiplier;
currenttip.add(new TranslationTextComponent("tooltip.storagedrawers.waila.limit", limit, multiplier));
}
}
if (config.get(new ResourceLocation(StorageDrawers.MOD_ID, "display.status"))) {
String attrib = "";
if (attr.isItemLocked(LockAttribute.LOCK_POPULATED))
attrib += (attrib.isEmpty() ? "" : ", ") + I18n.get("tooltip.storagedrawers.waila.locked");
if (attr.isVoid())
attrib += (attrib.isEmpty() ? "" : ", ") + I18n.get("tooltip.storagedrawers.waila.void");
//if (tile.getOwner() != null)
// attrib += (attrib.isEmpty() ? "" : ", ") + I18n.format("storagedrawers.waila.protected");
if (!attrib.isEmpty())
currenttip.add(new StringTextComponent(attrib));
}
}
}
}
|
package com.lingke.xvp.demo.controller.seller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.Rop.api.ApiException;
import com.Rop.api.domain.Product;
import com.Rop.api.domain.XvpSku;
import com.Rop.api.request.XvpProductCreateRequest;
import com.Rop.api.request.XvpProductDeleteRequest;
import com.Rop.api.request.XvpProductGetRequest;
import com.Rop.api.request.XvpProductQueryRequest;
import com.Rop.api.request.XvpProductUpdateRequest;
import com.Rop.api.request.XvpSkuAddskuRequest;
import com.Rop.api.request.XvpSkuDeleteskuRequest;
import com.Rop.api.request.XvpSkuGetskuRequest;
import com.Rop.api.response.XvpProductCreateResponse;
import com.Rop.api.response.XvpProductGetResponse;
import com.Rop.api.response.XvpProductQueryResponse;
import com.Rop.api.response.XvpSkuGetskuResponse;
import com.lingke.xvp.demo.XvpConstants;
import com.lingke.xvp.demo.XvpRopClient;
import com.lingke.xvp.demo.controller.request.ProductCreateRequest;
import com.lingke.xvp.demo.controller.request.ProductDeleteRequest;
import com.lingke.xvp.demo.controller.request.ProductGetRequest;
import com.lingke.xvp.demo.controller.request.ProductSkuGetRequest;
import com.lingke.xvp.demo.controller.request.ProductUpdateRequest;
import com.lingke.xvp.demo.controller.request.SkuAddRequest;
import com.lingke.xvp.demo.controller.request.SkuUpdateRequest;
import com.lingke.xvp.demo.controller.response.ProductQueryResponse;
import com.lingke.xvp.demo.controller.response.ProductResponse;
import com.lingke.xvp.demo.controller.response.ProductSkuGetListResponse;
import com.lingke.xvp.demo.controller.response.ProductSkuGetResponse;
import com.lingke.xvp.demo.controller.response.XvpResponse;
import com.lingke.xvp.demo.db.dao.DemoProduct;
import com.lingke.xvp.demo.utils.BeanCopyUtil;
import com.lingke.xvp.demo.utils.SessionUtil;
@RestController("seller_product")
@RequestMapping(value = "/seller/product")
public class ProductController {
@Autowired
private XvpRopClient ropClientAdapter;
/**
*
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public XvpResponse createProduct(@RequestBody ProductCreateRequest request) throws Exception {
XvpProductCreateRequest ropRequest = BeanCopyUtil.copy(request, XvpProductCreateRequest.class);
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setStore_id(Long.parseLong(SessionUtil.sellerGetStoreId()));
ropRequest.setVirtual_flg(0);
XvpProductCreateResponse productCreateResponse = ropClientAdapter.ropInvoke(ropRequest);
//FOR TESTING
// DemoProduct.addProduct(Long.valueOf(productCreateResponse.getProduct().getId()), request.getName());
for (SkuAddRequest skuRequest : request.getSku()) {
XvpSkuAddskuRequest ropSkuRequest = BeanCopyUtil.copy(skuRequest, XvpSkuAddskuRequest.class);
ropSkuRequest.setApp_id(ropClientAdapter.getAppId());
ropSkuRequest.setProduct_id(Long.valueOf(productCreateResponse.getProduct().getId()));
try {
ropClientAdapter.ropInvoke(ropSkuRequest);
} catch (Exception e) {
XvpProductDeleteRequest xvpProductDeleteRequest = new XvpProductDeleteRequest();
xvpProductDeleteRequest.setApp_id(ropClientAdapter.getAppId());
xvpProductDeleteRequest.setProduct_id(Long.valueOf(productCreateResponse.getProduct().getId()));
ropClientAdapter.ropInvoke(xvpProductDeleteRequest);
throw e;
}
}
return null;
}
/**
*
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/get", method = RequestMethod.POST)
@ResponseBody
public XvpResponse getProduct(@RequestBody ProductGetRequest request) throws Exception {
XvpProductGetRequest ropRequest = new XvpProductGetRequest();
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setProduct_id(request.getId());
XvpProductGetResponse ropResponse = ropClientAdapter.ropInvoke(ropRequest);
ProductResponse response = BeanCopyUtil.copy(ropResponse.getProduct(), ProductResponse.class);
// FOR TESTING
// String name = DemoProduct.getProductName(request.getId());
// if(name!=null){
// response.setName(name);
return response;
}
/**
*
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/delete", method = RequestMethod.POST)
@ResponseBody
public XvpResponse deleteProduct(@RequestBody ProductDeleteRequest request) throws ApiException {
XvpProductDeleteRequest ropRequest = new XvpProductDeleteRequest();
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setProduct_id(request.getId());
ropClientAdapter.ropInvoke(ropRequest);
return null;
}
/**
*
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/update", method = RequestMethod.POST)
@ResponseBody
public XvpResponse updateProduct(@RequestBody ProductUpdateRequest request) throws Exception {
List<SkuUpdateRequest> sku_list = request.getSku();
List<String> skuStrList = new ArrayList<String>();
for (SkuUpdateRequest sku : sku_list) {
String sku_str = sku.getSku_str().trim();
if(skuStrList.contains(sku_str)){
throw new RuntimeException("");
}
if(sku.getPrice() <= 0){
throw new RuntimeException("0");
}
skuStrList.add(sku_str);
}
XvpProductUpdateRequest ropRequest = BeanCopyUtil.copy(request, XvpProductUpdateRequest.class);
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setStore_id(Long.parseLong(SessionUtil.sellerGetStoreId()));
ropRequest.setVirtual_flg(0);
ropClientAdapter.ropInvoke(ropRequest);
for (SkuUpdateRequest sku : sku_list) {
if (sku.getId() != null) {
XvpSkuDeleteskuRequest ropSkuDelRequest = new XvpSkuDeleteskuRequest();
ropSkuDelRequest.setApp_id(ropClientAdapter.getAppId());
ropSkuDelRequest.setSku_id(sku.getId());
ropClientAdapter.ropInvoke(ropSkuDelRequest);
sku.setId(null);
}
}
for (SkuUpdateRequest sku : sku_list) {
XvpSkuAddskuRequest ropSkuAddRequest = BeanCopyUtil.copy(sku, XvpSkuAddskuRequest.class);
ropSkuAddRequest.setApp_id(ropClientAdapter.getAppId());
ropSkuAddRequest.setProduct_id(ropRequest.getProduct_id());
ropClientAdapter.ropInvoke(ropSkuAddRequest);
}
return null;
}
/**
*
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/query", method = RequestMethod.POST)
@ResponseBody
public XvpResponse queryProduct() throws Exception {
XvpProductQueryRequest ropRequest = new XvpProductQueryRequest();
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setPage_no(XvpConstants.PAGE_NO);
ropRequest.setPage_size(XvpConstants.PAGE_SIZE);
ropRequest.setStore_id(Long.parseLong(SessionUtil.sellerGetStoreId()));
XvpProductQueryResponse ropResponse = ropClientAdapter.ropInvoke(ropRequest);
ProductQueryResponse response = new ProductQueryResponse();
for (Product product : ropResponse.getProducts()) {
ProductResponse prodcutResponse = BeanCopyUtil.copy(product, ProductResponse.class);
response.add(prodcutResponse);
}
return response;
}
/**
* sku
*
* @param request
* @return
* @throws ApiException
*/
@RequestMapping(path = "/sku/get", method = RequestMethod.POST)
public XvpResponse getProductSku(@RequestBody ProductSkuGetRequest request) throws Exception {
XvpSkuGetskuRequest ropRequest = BeanCopyUtil.copy(request, XvpSkuGetskuRequest.class);
ropRequest.setApp_id(ropClientAdapter.getAppId());
ropRequest.setStore_id(Long.valueOf(SessionUtil.sellerGetStoreId()));
XvpSkuGetskuResponse ropResponse = ropClientAdapter.ropInvoke(ropRequest);
ProductSkuGetListResponse response = new ProductSkuGetListResponse();
for (XvpSku sku : ropResponse.getXvpskus()) {
ProductSkuGetResponse prodcutResponse = BeanCopyUtil.copy(sku, ProductSkuGetResponse.class);
response.add(prodcutResponse);
}
return response;
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.checks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.puppycrawl.tools.checkstyle.Definitions;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
public class TranslationCheck extends AbstractFileSetCheck {
/**
* A key is pointing to the warning message text for missing key
* in "messages.properties" file.
*/
public static final String MSG_KEY = "translation.missingKey";
/**
* A key is pointing to the warning message text for missing translation file
* in "messages.properties" file.
*/
public static final String MSG_KEY_MISSING_TRANSLATION_FILE =
"translation.missingTranslationFile";
/** Resource bundle which contains messages for TranslationCheck. */
private static final String TRANSLATION_BUNDLE =
"com.puppycrawl.tools.checkstyle.checks.messages";
/**
* A key is pointing to the warning message text for wrong language code
* in "messages.properties" file.
*/
private static final String WRONG_LANGUAGE_CODE_KEY = "translation.wrongLanguageCode";
/** Logger for TranslationCheck. */
private static final Log LOG = LogFactory.getLog(TranslationCheck.class);
/**
* Regexp string for default tranlsation files.
* For example, messages.properties.
*/
private static final String DEFAULT_TRANSLATION_REGEXP = "^.+\\..+$";
/**
* Regexp pattern for bundles names wich end with language code, followed by country code and
* variant suffix. For example, messages_es_ES_UNIX.properties.
*/
private static final Pattern LANGUAGE_COUNTRY_VARIANT_PATTERN =
CommonUtils.createPattern("^.+\\_[a-z]{2}\\_[A-Z]{2}\\_[A-Za-z]+\\..+$");
/**
* Regexp pattern for bundles names wich end with language code, followed by country code
* suffix. For example, messages_es_ES.properties.
*/
private static final Pattern LANGUAGE_COUNTRY_PATTERN =
CommonUtils.createPattern("^.+\\_[a-z]{2}\\_[A-Z]{2}\\..+$");
/**
* Regexp pattern for bundles names wich end with language code suffix.
* For example, messages_es.properties.
*/
private static final Pattern LANGUAGE_PATTERN =
CommonUtils.createPattern("^.+\\_[a-z]{2}\\..+$");
/** File name format for default translation. */
private static final String DEFAULT_TRANSLATION_FILE_NAME_FORMATTER = "%s.%s";
/** File name format with language code. */
private static final String FILE_NAME_WITH_LANGUAGE_CODE_FORMATTER = "%s_%s.%s";
/** Formatting string to form regexp to validate required tranlsations file names. */
private static final String REGEXP_FORMAT_TO_CHECK_REQUIRED_TRANSLATIONS =
"^%1$s\\_%2$s(\\_[A-Z]{2})?\\.%3$s$|^%1$s\\_%2$s\\_[A-Z]{2}\\_[A-Za-z]+\\.%3$s$";
/** Formatting string to form regexp to validate default tranlsations file names. */
private static final String REGEXP_FORMAT_TO_CHECK_DEFAULT_TRANSLATIONS = "^%s\\.%s$";
/** The files to process. */
private final Set<File> filesToProcess = Sets.newHashSet();
/** The base name regexp pattern. */
private Pattern baseNamePattern;
/**
* Language codes of required translations for the check (de, pt, ja, etc).
*/
private Set<String> requiredTranslations = Sets.newHashSet();
/**
* Creates a new {@code TranslationCheck} instance.
*/
public TranslationCheck() {
setFileExtensions("properties");
baseNamePattern = CommonUtils.createPattern("^messages.*$");
}
/**
* Sets the base name regexp pattern.
* @param baseName base name regexp.
*/
public void setBaseName(String baseName) {
baseNamePattern = CommonUtils.createPattern(baseName);
}
/**
* Sets language codes of required translations for the check.
* @param translationCodes a comma separated list of language codes.
*/
public void setRequiredTranslations(String... translationCodes) {
requiredTranslations = Sets.newHashSet(translationCodes);
validateUserSpecifiedLanguageCodes(requiredTranslations);
}
/**
* Validates the correctness of user specififed language codes for the check.
* @param languageCodes user specified language codes for the check.
*/
private void validateUserSpecifiedLanguageCodes(Set<String> languageCodes) {
for (String code : languageCodes) {
if (!isValidLanguageCode(code)) {
final LocalizedMessage msg = new LocalizedMessage(0, TRANSLATION_BUNDLE,
WRONG_LANGUAGE_CODE_KEY, new Object[] {code}, getId(), getClass(), null);
final String exceptionMessage = String.format(Locale.ROOT,
"%s [%s]", msg.getMessage(), TranslationCheck.class.getSimpleName());
throw new IllegalArgumentException(exceptionMessage);
}
}
}
/**
* Checks whether user specified language code is correct (is contained in available locales).
* @param userSpecifiedLanguageCode user specified language code.
* @return true if user specified language code is correct.
*/
private static boolean isValidLanguageCode(final String userSpecifiedLanguageCode) {
boolean valid = false;
final Locale[] locales = Locale.getAvailableLocales();
for (Locale locale : locales) {
if (userSpecifiedLanguageCode.equals(locale.toString())) {
valid = true;
break;
}
}
return valid;
}
@Override
public void beginProcessing(String charset) {
super.beginProcessing(charset);
filesToProcess.clear();
}
@Override
protected void processFiltered(File file, List<String> lines) {
// We just collecting files for processing at finishProcessing()
filesToProcess.add(file);
}
@Override
public void finishProcessing() {
super.finishProcessing();
final Set<ResourceBundle> bundles = groupFilesIntoBundles(filesToProcess, baseNamePattern);
for (ResourceBundle currentBundle : bundles) {
checkExistenceOfDefaultTranslation(currentBundle);
checkExistenceOfRequiredTranslations(currentBundle);
checkTranslationKeys(currentBundle);
}
}
/**
* Checks an existence of default translation file in the resource bundle.
* @param bundle resource bundle.
*/
private void checkExistenceOfDefaultTranslation(ResourceBundle bundle) {
final Optional<String> fileName = getMissingFileName(bundle, null);
if (fileName.isPresent()) {
logMissingTranslation(bundle.getPath(), fileName.get());
}
}
/**
* Checks an existence of translation files in the resource bundle.
* The name of translation file begins with the base name of resource bundle which is followed
* by '_' and a language code (country and variant are optional), it ends with the extension
* suffix.
* @param bundle resource bundle.
*/
private void checkExistenceOfRequiredTranslations(ResourceBundle bundle) {
for (String languageCode : requiredTranslations) {
final Optional<String> fileName = getMissingFileName(bundle, languageCode);
if (fileName.isPresent()) {
logMissingTranslation(bundle.getPath(), fileName.get());
}
}
}
/**
* Returns the name of translation file which is absent in resource bundle or Guava's Optional,
* if there is not missing translation.
* @param bundle resource bundle.
* @param languageCode language code.
* @return the name of translation file which is absent in resource bundle or Guava's Optional,
* if there is not missing translation.
*/
private static Optional<String> getMissingFileName(ResourceBundle bundle, String languageCode) {
final String fileNameRegexp;
final boolean searchForDefaultTranslation;
final String extension = bundle.getExtension();
final String baseName = bundle.getBaseName();
if (languageCode == null) {
searchForDefaultTranslation = true;
fileNameRegexp = String.format(Locale.ROOT, REGEXP_FORMAT_TO_CHECK_DEFAULT_TRANSLATIONS,
baseName, extension);
}
else {
searchForDefaultTranslation = false;
fileNameRegexp = String.format(Locale.ROOT,
REGEXP_FORMAT_TO_CHECK_REQUIRED_TRANSLATIONS, baseName, languageCode, extension);
}
Optional<String> missingFileName = Optional.empty();
if (!bundle.containsFile(fileNameRegexp)) {
if (searchForDefaultTranslation) {
missingFileName = Optional.of(String.format(Locale.ROOT,
DEFAULT_TRANSLATION_FILE_NAME_FORMATTER, baseName, extension));
}
else {
missingFileName = Optional.of(String.format(Locale.ROOT,
FILE_NAME_WITH_LANGUAGE_CODE_FORMATTER, baseName, languageCode, extension));
}
}
return missingFileName;
}
/**
* Logs that translation file is missing.
* @param filePath file path.
* @param fileName file name.
*/
private void logMissingTranslation(String filePath, String fileName) {
final MessageDispatcher dispatcher = getMessageDispatcher();
dispatcher.fireFileStarted(filePath);
log(0, MSG_KEY_MISSING_TRANSLATION_FILE, fileName);
fireErrors(filePath);
dispatcher.fireFileFinished(filePath);
}
/**
* Groups a set of files into bundles.
* Only files, which names match base name regexp pattern will be grouped.
* @param files set of files.
* @param baseNameRegexp base name regexp pattern.
* @return set of ResourceBundles.
*/
private static Set<ResourceBundle> groupFilesIntoBundles(Set<File> files,
Pattern baseNameRegexp) {
final Set<ResourceBundle> resourceBundles = Sets.newHashSet();
for (File currentFile : files) {
final String fileName = currentFile.getName();
final String baseName = extractBaseName(fileName);
final Matcher baseNameMatcher = baseNameRegexp.matcher(baseName);
if (baseNameMatcher.matches()) {
final String extension = Files.getFileExtension(fileName);
final String path = getPath(currentFile.getAbsolutePath());
final ResourceBundle newBundle = new ResourceBundle(baseName, path, extension);
final Optional<ResourceBundle> bundle = findBundle(resourceBundles, newBundle);
if (bundle.isPresent()) {
bundle.get().addFile(currentFile);
}
else {
newBundle.addFile(currentFile);
resourceBundles.add(newBundle);
}
}
}
return resourceBundles;
}
/**
* Searches for specific resource bundle in a set of resource bundles.
* @param bundles set of resource bundles.
* @param targetBundle target bundle to search for.
* @return Guava's Optional of resource bundle (present if target bundle is found).
*/
private static Optional<ResourceBundle> findBundle(Set<ResourceBundle> bundles,
ResourceBundle targetBundle) {
Optional<ResourceBundle> result = Optional.empty();
for (ResourceBundle currentBundle : bundles) {
if (targetBundle.getBaseName().equals(currentBundle.getBaseName())
&& targetBundle.getExtension().equals(currentBundle.getExtension())
&& targetBundle.getPath().equals(currentBundle.getPath())) {
result = Optional.of(currentBundle);
break;
}
}
return result;
}
/**
* Extracts the base name (the unique prefix) of resource bundle from translation file name.
* For example "messages" is the base name of "messages.properties",
* "messages_de_AT.properties", "messages_en.properties", etc.
* @param fileName the fully qualified name of the translation file.
* @return the extracted base name.
*/
private static String extractBaseName(String fileName) {
final String regexp;
final Matcher languageCountryVariantMatcher =
LANGUAGE_COUNTRY_VARIANT_PATTERN.matcher(fileName);
final Matcher languageCountryMatcher = LANGUAGE_COUNTRY_PATTERN.matcher(fileName);
final Matcher languageMatcher = LANGUAGE_PATTERN.matcher(fileName);
if (languageCountryVariantMatcher.matches()) {
regexp = LANGUAGE_COUNTRY_VARIANT_PATTERN.pattern();
}
else if (languageCountryMatcher.matches()) {
regexp = LANGUAGE_COUNTRY_PATTERN.pattern();
}
else if (languageMatcher.matches()) {
regexp = LANGUAGE_PATTERN.pattern();
}
else {
regexp = DEFAULT_TRANSLATION_REGEXP;
}
// We use substring(...) insead of replace(...), so that the regular expression does
// not have to be compiled each time it is used inside 'replace' method.
final String removePattern = regexp.substring("^.+".length(), regexp.length());
return fileName.replaceAll(removePattern, "");
}
/**
* Extracts path from a file name which contains the path.
* For example, if file nam is /xyz/messages.properties, then the method
* will return /xyz/.
* @param fileNameWithPath file name which contains the path.
* @return file path.
*/
private static String getPath(String fileNameWithPath) {
return fileNameWithPath
.substring(0, fileNameWithPath.lastIndexOf(File.separator));
}
/**
* Checks resource files in bundle for consistency regarding their keys.
* All files in bundle must have the same key set. If this is not the case
* an error message is posted giving information which key misses in which file.
* @param bundle resource bundle.
*/
private void checkTranslationKeys(ResourceBundle bundle) {
final Set<File> filesInBundle = bundle.getFiles();
if (filesInBundle.size() > 1) {
// build a map from files to the keys they contain
final Set<String> allTranslationKeys = Sets.newHashSet();
final SetMultimap<File, String> filesAssociatedWithKeys = HashMultimap.create();
for (File currentFile : filesInBundle) {
final Set<String> keysInCurrentFile = getTranslationKeys(currentFile);
allTranslationKeys.addAll(keysInCurrentFile);
filesAssociatedWithKeys.putAll(currentFile, keysInCurrentFile);
}
checkFilesForConsistencyRegardingTheirKeys(filesAssociatedWithKeys, allTranslationKeys);
}
}
/**
* Compares th the specified key set with the key sets of the given translation files (arranged
* in a map). All missing keys are reported.
* @param fileKeys a Map from translation files to their key sets.
* @param keysThatMustExist the set of keys to compare with.
*/
private void checkFilesForConsistencyRegardingTheirKeys(SetMultimap<File, String> fileKeys,
Set<String> keysThatMustExist) {
for (File currentFile : fileKeys.keySet()) {
final MessageDispatcher dispatcher = getMessageDispatcher();
final String path = currentFile.getPath();
dispatcher.fireFileStarted(path);
final Set<String> currentFileKeys = fileKeys.get(currentFile);
final Set<String> missingKeys = Sets.difference(keysThatMustExist, currentFileKeys);
if (!missingKeys.isEmpty()) {
for (Object key : missingKeys) {
log(0, MSG_KEY, key);
}
}
fireErrors(path);
dispatcher.fireFileFinished(path);
}
}
/**
* Loads the keys from the specified translation file into a set.
* @param file translation file.
* @return a Set object which holds the loaded keys.
*/
private Set<String> getTranslationKeys(File file) {
Set<String> keys = Sets.newHashSet();
InputStream inStream = null;
try {
inStream = new FileInputStream(file);
final Properties translations = new Properties();
translations.load(inStream);
keys = translations.stringPropertyNames();
}
catch (final IOException ex) {
logIoException(ex, file);
}
finally {
Closeables.closeQuietly(inStream);
}
return keys;
}
/**
* Helper method to log an io exception.
* @param exception the exception that occurred
* @param file the file that could not be processed
*/
private void logIoException(IOException exception, File file) {
String[] args = null;
String key = "general.fileNotFound";
if (!(exception instanceof FileNotFoundException)) {
args = new String[] {exception.getMessage()};
key = "general.exception";
}
final LocalizedMessage message =
new LocalizedMessage(
0,
Definitions.CHECKSTYLE_BUNDLE,
key,
args,
getId(),
getClass(), null);
final SortedSet<LocalizedMessage> messages = Sets.newTreeSet();
messages.add(message);
getMessageDispatcher().fireErrors(file.getPath(), messages);
LOG.debug("IOException occurred.", exception);
}
/** Class which represents a resource bundle. */
private static class ResourceBundle {
/** Bundle base name. */
private final String baseName;
/** Common extension of files which are included in the resource bundle. */
private final String extension;
/** Common path of files which are included in the resource bundle. */
private final String path;
/** Set of files which are included in the resource bundle. */
private final Set<File> files;
/**
* Creates a ResourceBundle object with specific base name, common files extension.
* @param baseName bundle base name.
* @param path common path of files which are included in the resource bundle.
* @param extension common extension of files which are included in the resource bundle.
*/
ResourceBundle(String baseName, String path, String extension) {
this.baseName = baseName;
this.path = path;
this.extension = extension;
files = Sets.newHashSet();
}
public String getBaseName() {
return baseName;
}
public String getPath() {
return path;
}
public String getExtension() {
return extension;
}
public Set<File> getFiles() {
return Collections.unmodifiableSet(files);
}
/**
* Adds a file into resource bundle.
* @param file file which should be added into resource bundle.
*/
public void addFile(File file) {
files.add(file);
}
/**
* Checks whether a resource bundle contains a file which name matches file name regexp.
* @param fileNameRegexp file name regexp.
* @return true if a resource bundle contains a file which name matches file name regexp.
*/
public boolean containsFile(String fileNameRegexp) {
boolean containsFile = false;
for (File currentFile : files) {
if (Pattern.matches(fileNameRegexp, currentFile.getName())) {
containsFile = true;
break;
}
}
return containsFile;
}
}
}
|
package com.rarchives.ripme.ripper.rippers;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.rarchives.ripme.ripper.AbstractHTMLRipper;
import com.rarchives.ripme.utils.Http;
public class WordpressComicRipper extends AbstractHTMLRipper {
private String pageTitle = "";
public WordpressComicRipper(URL url) throws IOException {
super(url);
}
// Test links (see also WordpressComicRipperTest.java)
private static List<String> explicit_domains = Arrays.asList(
"www.totempole666.com",
"buttsmithy.com",
"incase.buttsmithy.com",
"themonsterunderthebed.net",
"prismblush.com",
"www.konradokonski.com",
"freeadultcomix.com",
"thisis.delvecomic.com",
"tnbtu.com",
"shipinbottle.pepsaga.com",
"8muses.download",
"spyingwithlana.com"
);
private static List<String> theme1 = Arrays.asList(
"www.totempole666.com",
"buttsmithy.com",
"themonsterunderthebed.net",
"prismblush.com",
"www.konradokonski.com",
"thisis.delvecomic.com",
"tnbtu.com",
"spyingwithlana.com"
);
@Override
public String getHost() {
return url.toExternalForm().split("/")[2];
}
@Override
public String getDomain() {
return url.toExternalForm().split("/")[2];
}
@Override
public boolean canRip(URL url) {
String url_name = url.toExternalForm();
if (explicit_domains.contains(url_name.split("/")[2])) {
Pattern totempole666Pat = Pattern.compile("https?://www\\.totempole666.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher totempole666Mat = totempole666Pat.matcher(url.toExternalForm());
if (totempole666Mat.matches()) {
return true;
}
Pattern konradokonskiPat = Pattern.compile("https?:
Matcher konradokonskiMat = konradokonskiPat.matcher(url.toExternalForm());
if (konradokonskiMat.matches()) {
return true;
}
// This is hardcoded because it starts on the first page, unlike all the other
// konradokonski which start on the last page
konradokonskiPat = Pattern.compile("https?:
konradokonskiMat = konradokonskiPat.matcher(url.toExternalForm());
if (konradokonskiMat.matches()) {
return true;
}
Pattern buttsmithyPat = Pattern.compile("https?://buttsmithy.com/archives/comic/([a-zA-Z0-9_-]*)/?$");
Matcher buttsmithyMat = buttsmithyPat.matcher(url.toExternalForm());
if (buttsmithyMat.matches()) {
return true;
}
Pattern buttsmithyIncasePat = Pattern.compile("https?://incase.buttsmithy.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher buttsmithyIncaseMat = buttsmithyIncasePat.matcher(url.toExternalForm());
if (buttsmithyIncaseMat.matches()) {
return true;
}
Pattern theMonsterUnderTheBedPat = Pattern.compile("https?://themonsterunderthebed.net/\\?comic=([a-zA-Z0-9_-]*)/?$");
Matcher theMonsterUnderTheBedMat = theMonsterUnderTheBedPat.matcher(url.toExternalForm());
if (theMonsterUnderTheBedMat.matches()) {
return true;
}
Pattern prismblushPat = Pattern.compile("https?://prismblush.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher prismblushMat = prismblushPat.matcher(url.toExternalForm());
if (prismblushMat.matches()) {
return true;
}
Pattern freeadultcomixPat = Pattern.compile("https?://freeadultcomix.com/([a-zA-Z0-9_\\-]*)/?$");
Matcher freeadultcomixMat = freeadultcomixPat.matcher(url.toExternalForm());
if (freeadultcomixMat.matches()) {
return true;
}
Pattern thisisDelvecomicPat = Pattern.compile("https?://thisis.delvecomic.com/NewWP/comic/([a-zA-Z0-9_\\-]*)/?$");
Matcher thisisDelvecomicMat = thisisDelvecomicPat.matcher(url.toExternalForm());
if (thisisDelvecomicMat.matches()) {
return true;
}
Pattern comicsxxxPat = Pattern.compile("https?://comics-xxx.com/([a-zA-Z0-9_\\-]*)/?$");
Matcher comicsxxxMat = comicsxxxPat.matcher(url.toExternalForm());
if (comicsxxxMat.matches()) {
return true;
}
Pattern tnbtuPat = Pattern.compile("https?://tnbtu.com/comic/([0-9_\\-]*)/?$");
Matcher tnbtuMat = tnbtuPat.matcher(url.toExternalForm());
if (tnbtuMat.matches()) {
return true;
}
Pattern shipinbottlePat = Pattern.compile("https?://shipinbottle.pepsaga.com/\\?p=([0-9]*)/?$");
Matcher shipinbottleMat =shipinbottlePat.matcher(url.toExternalForm());
if (shipinbottleMat.matches()) {
return true;
}
Pattern eight_musesPat = Pattern.compile("https?://8muses.download/([a-zA-Z0-9_-]+)/?$");
Matcher eight_musesMat = eight_musesPat.matcher(url.toExternalForm());
if (eight_musesMat.matches()) {
return true;
}
Pattern spyingwithlanaPat = Pattern.compile("https?://spyingwithlana.com/comic/([a-zA-Z0-9_-]+)/?$");
Matcher spyingwithlanaMat = spyingwithlanaPat.matcher(url.toExternalForm());
if (spyingwithlanaMat.matches()) {
return true;
}
Pattern pa = Pattern.compile("^https?://8muses.download/\\?s=([a-zA-Z0-9-]*)");
Matcher ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return true;
}
Pattern pat = Pattern.compile("https?://8muses.download/page/\\d+/\\?s=([a-zA-Z0-9-]*)");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return true;
}
pat = Pattern.compile("https://8muses.download/category/([a-zA-Z0-9-]*)/?");
mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return true;
}
}
return false;
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern pa = Pattern.compile("^https?://8muses.download/\\?s=([a-zA-Z0-9-]*)");
Matcher ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return true;
}
Pattern pat = Pattern.compile("https?://8muses.download/page/\\d+/\\?s=([a-zA-Z0-9-]*)");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return true;
}
pat = Pattern.compile("https://8muses.download/category/([a-zA-Z0-9-]*)/?");
mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return true;
}
return false;
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select("#post_masonry > article > div > figure > a")) {
urlsToAddToQueue.add(elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
Pattern totempole666Pat = Pattern.compile("(?:https?://)?(?:www\\.)?totempole666.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher totempole666Mat = totempole666Pat.matcher(url.toExternalForm());
if (totempole666Mat.matches()) {
return "totempole666.com" + "_" + "The_cummoner";
}
Pattern buttsmithyPat = Pattern.compile("https?://buttsmithy.com/archives/comic/([a-zA-Z0-9_-]*)/?$");
Matcher buttsmithyMat = buttsmithyPat.matcher(url.toExternalForm());
if (buttsmithyMat.matches()) {
return "buttsmithy.com" + "_" + "Alfie";
}
Pattern konradokonskiPat = Pattern.compile("http:
Matcher konradokonskiMat = konradokonskiPat.matcher(url.toExternalForm());
if (konradokonskiMat.matches()) {
return "konradokonski.com_" + konradokonskiMat.group(1);
}
konradokonskiPat = Pattern.compile("https?:
konradokonskiMat = konradokonskiPat.matcher(url.toExternalForm());
if (konradokonskiMat.matches()) {
return "konradokonski.com_aquartzbead";
}
Pattern freeadultcomixPat = Pattern.compile("https?://freeadultcomix.com/([a-zA-Z0-9_\\-]*)/?$");
Matcher freeadultcomixMat = freeadultcomixPat.matcher(url.toExternalForm());
if (freeadultcomixMat.matches()) {
return getHost() + "_" + freeadultcomixMat.group(1);
}
Pattern thisisDelvecomicPat = Pattern.compile("https?://thisis.delvecomic.com/NewWP/comic/([a-zA-Z0-9_\\-]*)/?$");
Matcher thisisDelvecomicMat = thisisDelvecomicPat.matcher(url.toExternalForm());
if (thisisDelvecomicMat.matches()) {
return getHost() + "_" + "Delve";
}
Pattern prismblushPat = Pattern.compile("https?://prismblush.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher prismblushMat = prismblushPat.matcher(url.toExternalForm());
if (prismblushMat.matches()) {
return getHost() + "_" + prismblushMat.group(1);
}
Pattern buttsmithyIncasePat = Pattern.compile("https?://incase.buttsmithy.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher buttsmithyIncaseMat = buttsmithyIncasePat.matcher(url.toExternalForm());
if (buttsmithyIncaseMat.matches()) {
return getHost() + "_" + buttsmithyIncaseMat.group(1).replaceAll("-page-\\d", "").replaceAll("-pg-\\d", "");
}
Pattern comicsxxxPat = Pattern.compile("https?://comics-xxx.com/([a-zA-Z0-9_\\-]*)/?$");
Matcher comicsxxxMat = comicsxxxPat.matcher(url.toExternalForm());
if (comicsxxxMat.matches()) {
return getHost() + "_" + comicsxxxMat.group(1);
}
Pattern tnbtuPat = Pattern.compile("https?://tnbtu.com/comic/([0-9_\\-]*)/?$");
Matcher tnbtuMat = tnbtuPat.matcher(url.toExternalForm());
if (tnbtuMat.matches()) {
return getHost() + "_" + "The_Night_Belongs_to_Us";
}
Pattern shipinbottlePat = Pattern.compile("https?://shipinbottle.pepsaga.com/\\?p=([0-9]*)/?$");
Matcher shipinbottleMat =shipinbottlePat.matcher(url.toExternalForm());
if (shipinbottleMat.matches()) {
return getHost() + "_" + "Ship_in_bottle";
}
Pattern eight_musesPat = Pattern.compile("https?://8muses.download/([a-zA-Z0-9_-]+)/?$");
Matcher eight_musesMat = eight_musesPat.matcher(url.toExternalForm());
if (eight_musesMat.matches()) {
return getHost() + "_" + eight_musesMat.group(1);
}
Pattern spyingwithlanaPat = Pattern.compile("https?://spyingwithlana.com/comic/([a-zA-Z0-9_-]+)/?$");
Matcher spyingwithlanaMat = spyingwithlanaPat.matcher(url.toExternalForm());
if (spyingwithlanaMat.matches()) {
return "spyingwithlana_" + spyingwithlanaMat.group(1).replaceAll("-page-\\d", "");
}
return super.getAlbumTitle(url);
}
@Override
public String getGID(URL url) throws MalformedURLException {
String url_name = url.toExternalForm();
// We shouldn't need to return any GID
if (explicit_domains.contains(url_name.split("/")[2])) {
return "";
}
throw new MalformedURLException("You should never see this error message");
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
String nextPage = "";
Element elem = null;
if (theme1.contains(getHost())) {
elem = doc.select("a.comic-nav-next").first();
if (elem == null) {
throw new IOException("No more pages");
}
nextPage = elem.attr("href");
} else if (getHost().contains("shipinbottle.pepsaga.com")) {
elem = doc.select("td.comic_navi_right > a.navi-next").first();
if (elem == null) {
throw new IOException("No more pages");
}
nextPage = elem.attr("href");
}
if (nextPage.equals("")) {
throw new IOException("No more pages");
} else {
return Http.url(nextPage).get();
}
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (theme1.contains(getHost())) {
Element elem = doc.select("div.comic-table > div#comic > a > img").first();
// If doc is the last page in the comic then elem.attr("src") returns null
// because there is no link <a> to the next page
if (elem == null) {
elem = doc.select("div.comic-table > div#comic > img").first();
}
// Check if this is a site where we can get the page number from the title
if (url.toExternalForm().contains("buttsmithy.com")) {
// Set the page title
pageTitle = doc.select("meta[property=og:title]").attr("content");
pageTitle = pageTitle.replace(" ", "");
pageTitle = pageTitle.replace("P", "p");
}
if (url.toExternalForm().contains("www.totempole666.com")) {
String postDate = doc.select("span.post-date").first().text().replaceAll("/", "_");
String postTitle = doc.select("h2.post-title").first().text().replaceAll("
pageTitle = postDate + "_" + postTitle;
}
if (url.toExternalForm().contains("themonsterunderthebed.net")) {
pageTitle = doc.select("title").first().text().replaceAll("
pageTitle = pageTitle.replace("“", "");
pageTitle = pageTitle.replace("”", "");
pageTitle = pageTitle.replace("The Monster Under the Bed", "");
pageTitle = pageTitle.replace("–", "");
pageTitle = pageTitle.replace(",", "");
pageTitle = pageTitle.replace(" ", "");
}
result.add(elem.attr("src"));
}
// TODO review the above comment which no longer applies -- see if there's a refactoring we should do here.
if (url.toExternalForm().contains("freeadultcomix.com")) {
for (Element elem : doc.select("div.single-post > p > img.aligncenter")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("comics-xxx.com")) {
for (Element elem : doc.select("div.single-post > center > p > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("shipinbottle.pepsaga.com")) {
for (Element elem : doc.select("div#comic > div.comicpane > a > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("8muses.download")) {
for (Element elem : doc.select("div.popup-gallery > figure > a")) {
result.add(elem.attr("href"));
}
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
// Download the url with the page title as the prefix
// so we can download them in any order (And don't have to rerip the whole site to update the local copy)
if (getHost().contains("buttsmithy.com")
|| getHost().contains("www.totempole666.com")
|| getHost().contains("themonsterunderthebed.net")) {
addURLToDownload(url, pageTitle + "_");
}
if (getHost().contains("tnbtu.com")) {
// We need to set the referrer header for tnbtu
addURLToDownload(url, getPrefix(index), "","http:
} else {
// If we're ripping a site where we can't get the page number/title we just rip normally
addURLToDownload(url, getPrefix(index));
}
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
}
|
package cubicchunks.asm.mixin.core.common;
import cubicchunks.CubicChunks;
import cubicchunks.server.chunkio.ICubeIO;
import cubicchunks.world.ICubicSaveHandler;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.chunk.storage.RegionFileCache;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.io.IOException;
import javax.annotation.ParametersAreNonnullByDefault;
// a hook for flush()
// many mods already assume AnvilSaveHandler is always used, so we assume the same and hope for the best
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@Mixin(AnvilSaveHandler.class)
public class MixinAnvilSaveHandler implements ICubicSaveHandler {
private ICubeIO cubeIo;
@Inject(method = "flush", at = @At("RETURN"))
public void onClearRefs(CallbackInfo cbi) throws IOException {
if (cubeIo == null) {
CubicChunks.bigWarning("cubeIo not initializes in save handler! If this happens frequently it's likely a major issue!");
return;
}
cubeIo.flush();
}
@Override public void initCubic(ICubeIO cubeIo) {
if (this.cubeIo == null) {
CubicChunks.LOGGER.debug("Initializing cubeIo for cubic chunks save handler!");
this.cubeIo = cubeIo;
}
}
}
|
package de.devgruppe.fundiscordbot.command.commands;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import de.devgruppe.fundiscordbot.command.Command;
import de.devgruppe.fundiscordbot.command.CommandResponse;
import de.devgruppe.fundiscordbot.util.HttpRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import net.dv8tion.jda.core.entities.Message;
public class MemeCommand extends Command {
public MemeCommand() {
super("meme", "<Name> [<Text oben>[;<Text unten>]]", "Erstellt einen Meme");
}
@Override
public CommandResponse triggerCommand(Message message, String[] args) {
try {
if (args.length < 1) {
return CommandResponse.SYNTAX_PRINTED;
}
JsonParser parser = new JsonParser();
StringBuilder urlRequest = new StringBuilder();
urlRequest.append(args[0]).append("/");
if (args.length >= 2) {
StringBuilder texts = new StringBuilder();
for (int i = 1; i < args.length; i++) {
texts.append(args[i]).append(" ");
}
String textString = texts.toString();
textString = textString.replace("/", "~s");
textString = textString.replace("?", "~q");
textString = textString.replace("%", "~p");
textString = textString.replace("
textString = textString.replace("\"", "''");
if (textString.contains(";")) {
int count = textString.length() - textString.replace(";", "").length();
if (count > 1) {
message.getTextChannel().sendMessage("Du darfst maximal ein Semikolon(``;``) in deine Nachricht schreiben!").complete();
return CommandResponse.ACCEPTED;
}
String[] splitText = textString.split(";");
urlRequest.append(splitText[0]).append("/").append(splitText[1]);
} else {
urlRequest.append(texts.toString());
}
HttpRequest.RequestResponse res = HttpRequest.performRequest(new HttpRequest.RequestBuilder(MemeNamesCommand.API_URL + MemeNamesCommand.TEMPLATE_URL + urlRequest.toString(), HttpRequest.HttpRequestMethod.GET)
.addHeader("User-Agent", "Mozilla/5.0")
.addHeader("Accept", "application/json")
.setReadTimeout(15000));
JsonElement jsonElement = new JsonParser().parse(res.getResultMessage());
JsonObject jsonObject = jsonElement.getAsJsonObject();
jsonObject = jsonObject.getAsJsonObject("direct");
message.getTextChannel().sendMessage(jsonObject.get("masked").getAsString()).queue();
return CommandResponse.ACCEPTED;
}else{
return CommandResponse.SYNTAX_PRINTED;
}
} catch (FileNotFoundException exe){
message.getTextChannel().sendMessage("Meme konnte nicht gefunden werden! Versuche ``!memes``").queue();
} catch (IOException e) {
e.printStackTrace();
}
return CommandResponse.ACCEPTED;
}
}
|
package de.rwth.idsg.velocity.repository;
import de.rwth.idsg.velocity.domain.Address;
import de.rwth.idsg.velocity.domain.Customer;
import de.rwth.idsg.velocity.web.rest.BackendException;
import de.rwth.idsg.velocity.web.rest.dto.modify.CreateEditCustomerDTO;
import de.rwth.idsg.velocity.web.rest.dto.view.ViewCustomerDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class CustomerRepositoryImpl implements CustomerRepository {
private static final Logger log = LoggerFactory.getLogger(CustomerRepositoryImpl.class);
private enum Operation { CREATE, UPDATE };
private enum FindType { ALL, BY_NAME, BY_LOGIN };
@PersistenceContext
EntityManager em;
@Override
public List<ViewCustomerDTO> findAll() {
CriteriaBuilder builder = em.getCriteriaBuilder();
return em.createQuery(
getQuery(builder, FindType.ALL, null, null, null)
).getResultList();
}
@Override
public List<ViewCustomerDTO> findbyName(String firstname, String lastname) throws BackendException {
CriteriaBuilder builder = em.getCriteriaBuilder();
List<ViewCustomerDTO> list = em.createQuery(
getQuery(builder, FindType.BY_NAME, firstname, lastname, null)
).getResultList();
if (list.isEmpty()) {
throw new BackendException("No customer found with name " + firstname + " " + lastname);
} else {
return list;
}
}
@Override
public ViewCustomerDTO findbyLogin(String login) throws BackendException {
CriteriaBuilder builder = em.getCriteriaBuilder();
try {
return em.createQuery(
getQuery(builder, FindType.BY_LOGIN, null, null, login)
).getSingleResult();
} catch (NoResultException e) {
throw new BackendException("No customer found with login " + login);
}
}
@Override
public void activate(long userId) throws BackendException {
Customer customer = getCustomerEntity(userId);
try {
customer.setIsActivated(true);
em.merge(customer);
log.debug("Activated customer {}", customer);
} catch (Exception e) {
throw new BackendException("Failed to activate customer with userId " + userId);
}
}
@Override
public void deactivate(long userId) throws BackendException {
Customer customer = getCustomerEntity(userId);
try {
customer.setIsActivated(false);
em.merge(customer);
log.debug("Deactivated customer {}", customer);
} catch (Exception e) {
throw new BackendException("Failed to deactivate customer with userId " + userId);
}
}
@Override
public void create(CreateEditCustomerDTO dto) throws BackendException {
Customer customer = new Customer();
setFields(customer, dto, Operation.CREATE);
try {
em.persist(customer);
log.debug("Created new customer {}", customer);
} catch (EntityExistsException e) {
throw new BackendException("This customer exists already.");
} catch (Exception e) {
throw new BackendException("Failed to create a new customer.");
}
}
@Override
public void update(CreateEditCustomerDTO dto) throws BackendException {
final Long userId = dto.getUserId();
if (userId == null) {
return;
}
Customer customer = getCustomerEntity(userId);
try {
setFields(customer, dto, Operation.UPDATE);
em.merge(customer);
log.debug("Updated customer {}", customer);
} catch (Exception e) {
throw new BackendException("Failed to update customer with userId " + userId);
}
}
@Override
public void delete(long userId) throws BackendException {
Customer customer = getCustomerEntity(userId);
try {
em.remove(customer);
log.debug("Deleted customer {}", customer);
} catch (Exception e) {
throw new BackendException("Failed to delete customer with userId " + userId);
}
}
/**
* Returns a customer, or throws exception when no customer exists.
*
*/
private Customer getCustomerEntity(long userId) throws BackendException {
Customer customer = em.find(Customer.class, userId);
if (customer == null) {
throw new BackendException("No customer with userId " + userId);
} else {
return customer;
}
}
/**
* This method sets the fields of the customer to the values in DTO.
*
*/
private void setFields(Customer customer, CreateEditCustomerDTO dto, Operation operation) {
// TODO: Should the login be changeable? Who sets the field? Clarify!
customer.setLogin(dto.getLogin());
customer.setCustomerId(dto.getCustomerId());
customer.setCardId(dto.getCardId());
customer.setFirstname(dto.getFirstname());
customer.setLastname(dto.getLastname());
customer.setBirthday(dto.getBirthday());
customer.setIsActivated(dto.getIsActivated());
switch (operation) {
case CREATE:
// for create (brand new address entity)
customer.setAddress(dto.getAddress());
break;
case UPDATE:
// for edit (keep the address ID)
Address add = customer.getAddress();
Address dtoAdd = dto.getAddress();
add.setStreetAndHousenumber(dtoAdd.getStreetAndHousenumber());
add.setZip(dtoAdd.getZip());
add.setCity(dtoAdd.getCity());
add.setCountry(dtoAdd.getCountry());
break;
}
}
/**
* This method returns the query to get information of customers for various lookup cases
*
*/
private CriteriaQuery<ViewCustomerDTO> getQuery(CriteriaBuilder builder, FindType findType,
String firstname, String lastname,
String login) {
CriteriaQuery<ViewCustomerDTO> criteria = builder.createQuery(ViewCustomerDTO.class);
Root<Customer> root = criteria.from(Customer.class);
Join<Customer, Address> addressJoin = root.join("address", JoinType.LEFT);
criteria.select(
builder.construct(
ViewCustomerDTO.class,
root.get("userId"),
root.get("login"),
root.get("customerId"),
root.get("firstname"),
root.get("lastname"),
root.get("isActivated"),
root.get("birthday"),
root.get("cardId"),
addressJoin.get("streetAndHousenumber"),
addressJoin.get("zip"),
addressJoin.get("city"),
addressJoin.get("country")
)
);
switch (findType) {
case ALL:
break;
// Case insensitive search
case BY_NAME:
Path<String> firstPath = root.get("firstname");
Expression<String> firstLower = builder.lower(firstPath);
Path<String> lastPath = root.get("lastname");
Expression<String> lastLower = builder.lower(lastPath);
criteria.where(
builder.and(
builder.equal(firstLower, firstname.toLowerCase()),
builder.equal(lastLower, lastname.toLowerCase())
)
);
break;
// Case insensitive search
case BY_LOGIN:
Path<String> loginPath = root.get("login");
Expression<String> loginLower = builder.lower(loginPath);
criteria.where(
builder.equal(loginLower, login.toLowerCase())
);
break;
}
return criteria;
}
}
|
package de.sldk.mc.metrics.player;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Fetches player stats stored in
* <code>data/world/stats/<UUID>.json</code> files.
*/
public class PlayerStatisticLoaderFromFile implements PlayerStatisticLoader {
private final Plugin plugin;
private final Logger logger;
private final Map<UUID, Map<Enum<?>, Integer>> fileData;
private static final Map<String, Enum<?>> mapStatNameToStat = Arrays
.stream(PlayerStatisticLoaderFromBukkit.STATISTICS)
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e));
public PlayerStatisticLoaderFromFile(Plugin plugin) {
this.plugin = plugin;
this.logger = plugin.getLogger();
fileData = readPlayerStatsFiles();
}
@Override
public Map<Enum<?>, Integer> getPlayerStatistics(OfflinePlayer offlinePlayer) {
final UUID uuid = offlinePlayer.getUniqueId();
if (fileData.containsKey(uuid)) {
return fileData.get(uuid);
} else {
return new HashMap<>();
}
}
/**
* Reads all valid files in the <code>stats</code> folder and maps them to a
* player.
*/
private Map<UUID, Map<Enum<?>, Integer>> readPlayerStatsFiles() {
try {
File minecraftDataFolder = plugin.getServer().getWorldContainer().getCanonicalFile();
Path statsFolder = Paths.get(minecraftDataFolder.getAbsolutePath(), "world", "stats");
if (!Files.exists(statsFolder)) {
return new HashMap<>();
}
logger.fine("Reading player stats from folder " + statsFolder.toString());
try (Stream<Path> statFiles = Files.walk(statsFolder)) {
return statFiles.filter(Files::isRegularFile)
.filter(this::isFileNameUuid)
.peek(path -> logger.fine("Found player stats file: " + path.getFileName().toString()))
.collect(Collectors.toMap(this::fileNameToUuid, path -> {
try {
return getPlayersStats(path);
} catch (Exception e) {
String msg = String.format("Could not read player stats from JSON at '%s'", path);
logger.log(Level.FINE, msg, e);
return new HashMap<>();
}
}));
}
} catch (Exception e) {
logger.log(Level.FINE, "Failed to read player stats from file. ", e);
return new HashMap<>();
}
}
/**
* Given a player's stats json file, map each stat to a value.
*/
private Map<Enum<?>, Integer> getPlayersStats(Path path) throws IOException {
DocumentContext ctx = JsonPath.parse(path.toFile());
Map<String, Object> fileStats = ctx.read(JsonPath.compile("$.stats.minecraft:custom"));
return fileStats.keySet().stream().filter(mapStatNameToStat::containsKey)
.filter(e -> fileStats.get(e) instanceof Integer)
.collect(Collectors.toMap(mapStatNameToStat::get, e -> (Integer) fileStats.get(e)));
}
private boolean isFileNameUuid(Path path) {
try {
fileNameToUuid(path);
} catch (Exception e) {
String msg = String.format("Could not extract valid player UUID from player stats file '%s'", path);
logger.log(Level.FINE, msg, e);
return false;
}
return true;
}
private UUID fileNameToUuid(Path path) {
String uuidPart = path.getFileName().toString().split("\\.")[0];
return UUID.fromString(uuidPart);
}
}
|
package eu.esit4sip.tools.bsslurper;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IntegratedTagAndPageFetcher {
static HttpClient client = Util.createTolerantHttpClient();
static String baseUrl = "https://wiki.esit4sip.eu";
static Pattern internalImgPattern = Pattern.compile("<img src=\"([^\"]*/([^/\"]*))\""),
internalLinkPattern = Pattern.compile("<a href=\"(" + baseUrl + "/bin/view/[^\"]*)\"( |>)");
abstract class Spider {
Spider(List<String> paths) {
this.paths = paths;
}
List<String> paths;
String currentPath;
public void run() {
try {
for(String path : paths) {
currentPath = baseUrl + path;
System.out.println("(" + getClass().getSimpleName() + ") Fetching " + currentPath);
HttpResponse response = client.execute(new HttpGet(baseUrl + path));
processResponse(EntityUtils.toString(response.getEntity()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
abstract void processResponse(String body);
byte[] byteBuff = new byte[10240];
public void fetchFile(String filePath, String receivePath) throws IOException {
System.out.println("Saving file " + filePath);
HttpResponse response = client.execute(new HttpGet(baseUrl + filePath));
InputStream inS = response.getEntity().getContent();
String dir = receivePath.substring(0, receivePath.lastIndexOf('/'));
System.out.println("Mkdir dir " + dir);
new File(dir).mkdirs();
FileOutputStream fOut = new FileOutputStream(receivePath);
int r = 0;
while((r=inS.read(byteBuff))>-1) {
fOut.write(byteBuff, 0, r);
}
fOut.flush(); fOut.close();
}
}
class TagsListFetcher extends Spider {
TagsListFetcher(String tagsList) { super(Arrays.asList(tagsList));}
@Override
void processResponse(String body) {
Document doc = Jsoup.parse(body);
Map<String,String> currentTerms = null;
for(Element child :doc.getElementsByTag("body").first().children()) {
if("h2".equals(child.nodeName())) {
currentTerms = new HashMap<String,String>();
topicDivisions.put(child.text(), currentTerms);
} else if("ul".equals(child.nodeName()) && currentTerms!=null) {
for(Element li: child.children()) {
String text = li.text();
if(text.equals("...")) continue;
int p = text.indexOf(":"), q = text.indexOf(")", p+1);
if(p==-1 || q == -1) {
System.err.println("Term badly formed: " + text);
} else {
currentTerms.put(text.substring(0,p).trim(),
text.substring(q+1).trim());
}
}
}
}
}
}
class TagPagesFetcher extends Spider {
TagPagesFetcher(List<String> list) { super(list);}
@Override
void processResponse(String body) {
String tag = currentPath.replaceAll(".*tag=(.*)","$1");
Document document = Jsoup.parse(body);
Element content = document.getElementsByClass("xcontent").first();
Elements as = content.getElementsByTag("a");
if(as!=null) for(Element a: as) {
String url = baseUrl + a.attr("href");
if(url.contains("/bin/export")) continue;
String path = Util.computePath(url, baseUrl);
// only accept experience reports
if(!path.startsWith("/ExperienceReports") &&
!path.startsWith("/Scenarios/") &&
!path.startsWith("/Patterns/")) {
continue;
}
// do not accept parametrized docs
if(path.contains("?"))
continue;
Set<String> tagPages = tagsPages.get(tag);
if(tagPages == null) {
tagPages = new TreeSet<String>();
tagsPages.put(tag, tagPages);
}
tagPages.add(path);
}
}
}
class PagesFetcher extends Spider {
PagesFetcher(String url) { super(Arrays.asList(url, url + "?xpage=plain"));}
@Override
void processResponse(String body) {
try {
if(currentPath.endsWith("xpage=plain")) {
// first reformulate and fetch pictures
StringBuffer buff = new StringBuffer(body);
Matcher matcher = internalImgPattern.matcher(buff);
int off = 0;
while(matcher.find(off)) {
String fileName = matcher.group(2), filePath = matcher.group(1);
fileName = fileName.replaceAll("\\??width=[0-9]+\\&?","");
super.fetchFile(filePath, "out/pictures/" + fileName);
fileName = "data/pictures/" + fileName;
buff.replace(matcher.start(), matcher.end(), "<img src=\"" + fileName + "\" ");
off = matcher.start()+ fileName.length();
}
// then reformulate internal links
matcher = internalLinkPattern.matcher(buff);
System.out.println("Pattern: " + internalLinkPattern);
off = 0;
while(matcher.find(off)) {
System.out.println("Found href " + matcher.group());
buff.replace(matcher.start(), matcher.end(), "<a onclick=\"displayArticle('" +
Util.computePageFromUrl(matcher.group(1),baseUrl).replaceAll("__","_") + ".html'); return false;\"" + matcher.group(2));
off = matcher.start()+1;
}
body = buff.toString();
// simply store the page content
File file = Util.getOutputFile(
Util.computePageFromUrl(currentPath, baseUrl));
Writer out = new OutputStreamWriter( new FileOutputStream(file));
int len = body.length();
int l = body.indexOf("<h1 id=\"HLinks\"><span>Links</span></h1>");
if(l>-1) body = body.substring(0,l);
l = body.indexOf("<h1 id=\"HMetadata\"><span>Metadata</span></h1>");
if(l>-1) body = body.substring(0,l);
l = body.indexOf("<h1 id=\"HInformation\"><span>Information</span></h1>");
if(l>-1) body = body.substring(0,l);
out.write(body);
out.flush();
out.close();
// put the start of the content into the content, max 100 chars
// first remove the <h1> in there
int p = body.indexOf("</h1>");
if(p>-1) body = body.substring(p+"</h1>".length());
// then remove all tags
body = body.replaceAll("<[^>]*>","");
body = body.replaceAll("\r|\n|\t| "," ");
if(body.startsWith("Description:")) body = body.substring("Description:".length());
if(body.length()>100) {
// get last period
for(int i=0; i<100; ) {
p = i;
i = body.indexOf(".",i+1);
}
// include the period
p = p+1;
if(p>100 || p<50) p = 100;
body = body.substring(0,p);
if(p<100) body = body + "...";
}
pageContent.put(file.getName(), body);
} else {
// grasp the title
Document doc = Jsoup.parse(body);
Element elt = doc.getElementsByTag("title").first();
String name = Util.computePath(currentPath, baseUrl);
if(elt!=null) {
String title = elt.text();
if(title.endsWith(" - XWiki"))
title = title.substring(0, title.length()-" - XWiki".length());
title = title .replaceAll("\\([^)]*\\)", "");
if(title.endsWith(".WebHome")) title = title.substring(0, title.length()-".WebHome".length());
if(title.endsWith(".WebHome)")) title = title.substring(0, title.length()-".WebHome)".length());
title = title.trim();
pageTitles.put(name, title);
} else
pageTitles.put(name, "--missing-title
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// data structures
Map<String, Set<String>> tagsPages = new TreeMap<String, Set<String>>();
Map<String, Map<String,String>> topicDivisions = new TreeMap<String, Map<String, String>>();
Map<String, String> pageTitles = new TreeMap<String, String>(), pageContent = new TreeMap<String,String>();
public void run() {
// first fetch the tags
Spider f = new TagsListFetcher("/bin/view/BabySteps/NavigationTags/?xpage=plain");
f.run();
// then fetch the tags and the corresponding pages' URLs
for(String headLine: topicDivisions.keySet()) {
for(String tag: topicDivisions.get(headLine).keySet()) {
f = new TagPagesFetcher(Arrays.asList("/bin/view/Main/Tags?do=viewTag&tag=" + tag));
f.run();
}
}
// collect all pages in a set
Set<String> pages = new TreeSet<String>();
for(String tag: tagsPages.keySet()) {
for(String page: tagsPages.get(tag))
pages.add(page);
}
// now fetch all pages (and their title)
for(String pagePath: pages) {
f = new PagesFetcher("/bin/view" + pagePath);
f.run();
}
Set<String> tagsSet = new TreeSet(tagsPages.keySet());
for(String tag: tagsSet) {
Set<String> newPages = new TreeSet<String>();
for(String page: tagsPages.get(tag)) {
newPages.add(Util.getOutputFile(Util.computePageFromUrl(page, baseUrl)).getName());
}
tagsPages.put(tag, newPages);
}
Map<String,String> pageTitles2 = new TreeMap<String,String>();
for(Map.Entry<String,String>p: pageTitles.entrySet()) {
pageTitles2.put(Util.getOutputFile(Util.computePageFromUrl(p.getKey(), baseUrl)).getName(), p.getValue());
}
System.out.println(" ================ tags =============== ");
System.out.println(topicDivisions);
System.out.println(" ================ tagsPages =============== ");
System.out.println(tagsPages);
System.out.println(" ================ pages =============== ");
System.out.println(pageTitles2);
// output the json objects (all-tags.json from topicDivisions, tagsPages.json, pages.json
// JSON Tags for the web-site are like
// [ {"groupname":"Domain", "tags": ["math":"Mathematics", ...]},
List<Map<String,Object>> tagsJson = new LinkedList<Map<String,Object>>();
for(String groupName: topicDivisions.keySet()) {
Map<String, Object> group = new HashMap<String,Object>();
group.put("groupname", groupName);
Map<String,String> tags = new TreeMap<String,String>();
//List<String> tags = new LinkedList<String>();
for(Map.Entry<String,String> entry: topicDivisions.get(groupName).entrySet()) {
tags.put(entry.getKey(), entry.getValue());
//tags.add(entry.getKey());
}
group.put("tags", tags);
tagsJson.add(group);
}
writeMap("tags.json", tagsJson);
// JSON articles.json sample:
// [ {"name":"Article 1", "description":"Lorem", "url":"article1.html", "tags": ["mathematics", "Tag 12", "tablets"] }, ...]
List<Map<String,Object>> articlesJSON = new LinkedList<Map<String,Object>> ();
for(Map.Entry<String,String> pageAndTitle: pageTitles2.entrySet()) {
// now fetch the tags
Map<String, Object> article = new HashMap<String,Object>();
String pageName = pageAndTitle.getKey();
article.put("url", pageName);
article.put("name", pageAndTitle.getValue());
article.put("id", DigestUtils.md5Hex(pageName));
List<String> tags = new LinkedList<String>();
for(String tag: tagsPages.keySet()) {
for(String p: tagsPages.get(tag)) {
if(pageName.equals(p)) tags.add(tag);
}
}
article.put("tags", tags);
article.put("description", pageContent.get(pageName));
articlesJSON.add(article);
}
writeMap("articles.json", articlesJSON);
//writeMap("pages.json", pageTitles2);
}
private void writeMap(String fileName, Object map) {
try {
File outputFile = Util.getOutputFile(fileName);
System.out.println("Outputting: " + outputFile);
Writer out = new OutputStreamWriter(new FileOutputStream(outputFile),"utf-8");
JsonConfig config = new JsonConfig();
out.write(JSONSerializer.toJSON(map, config).toString());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new IntegratedTagAndPageFetcher().run();
}
}
|
package eu.fusepool.rdfizer.marec.xslt.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.xml.resolver.tools.ResolvingXMLFilter;
import org.xml.sax.InputSource;
import eu.fusepool.rdfizer.marec.xslt.MarecXMLReader;
import eu.fusepool.rdfizer.marec.xslt.ResourceURIResolver;
import eu.fusepool.rdfizer.marec.xslt.XMLProcessor;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
/**
* @author giorgio
* @author luigi
*
*/
public class PatentXSLTProcessor implements XMLProcessor {
private TransformerFactory tFactory;
public PatentXSLTProcessor() {
//just referencing the class to make sure it's in the OSGi import and available
if (net.sf.saxon.TransformerFactoryImpl.class == null) {
throw new RuntimeException("You'll never get this exception");
}
tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", this.getClass().getClassLoader());
}
public InputStream processXML(InputStream is) throws TransformerException {
URIResolver defResolver = tFactory.getURIResolver();
ResourceURIResolver customResolver = new ResourceURIResolver(defResolver);
tFactory.setURIResolver(customResolver);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream xslIs = this.getClass().getResourceAsStream("/xsl/marec.xsl");
StreamSource xlsSS = new StreamSource(xslIs);
Transformer transformer = tFactory.newTransformer(xlsSS);
InputSource inputSource = new InputSource(is);
ResolvingXMLFilter filter = new ResolvingXMLFilter(new MarecXMLReader());
Source saxSource = new SAXSource(filter, inputSource);
StreamResult sRes = new StreamResult(outputStream);
transformer.transform(saxSource, sRes);
return new ByteArrayInputStream(outputStream.toByteArray());
}
}
|
package fi.helsinki.cs.tmc.cli.command;
import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.command.core.Command;
import fi.helsinki.cs.tmc.cli.command.core.CommandInterface;
import fi.helsinki.cs.tmc.cli.io.Io;
import fi.helsinki.cs.tmc.cli.tmcstuff.CourseInfo;
import fi.helsinki.cs.tmc.cli.tmcstuff.CourseInfoIo;
import fi.helsinki.cs.tmc.cli.tmcstuff.DirectoryUtil;
import fi.helsinki.cs.tmc.cli.tmcstuff.TmcUtil;
import fi.helsinki.cs.tmc.core.TmcCore;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@Command(name = "download", desc = "Download exercises for a specific course")
public class DownloadExercisesCommand implements CommandInterface {
private Application app;
public DownloadExercisesCommand(Application app) {
this.app = app;
}
@Override
public void run(String[] args, Io io) {
Course course;
TmcCore core;
if (args.length == 0) {
io.println("You must give course name as an argument.");
io.println("Usage: tmc download COURSE");
return;
}
core = this.app.getTmcCore();
if (core == null) {
return;
}
DirectoryUtil dirUtil = new DirectoryUtil();
course = TmcUtil.findCourse(core, args[0]);
if (course == null) {
io.println("Course doesn't exist.");
return;
}
List<Exercise> exercises = TmcUtil.downloadAllExercises(core, course);
io.println(exercises.toString());
Path configFile = Paths.get(System.getProperty("user.dir"))
.resolve(args[0])
.resolve(CourseInfoIo.COURSE_CONFIG);
CourseInfoIo infoIo = new CourseInfoIo(configFile);
CourseInfo info = app.createCourseInfo(args[0]);
info.setExercises(exercises);
infoIo.save(info);
}
}
|
package fr.openent.viescolaire.service.impl;
import fr.openent.Viescolaire;
import fr.openent.viescolaire.service.EleveService;
import fr.openent.viescolaire.service.UtilsService;
import fr.wseduc.webutils.Either;
import io.vertx.core.eventbus.Message;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.entcore.common.neo4j.Neo4j;
import org.entcore.common.neo4j.Neo4jResult;
import org.entcore.common.sql.Sql;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.entcore.common.sql.SqlResult.validResultHandler;
public class DefaultUtilsService implements UtilsService{
private final Neo4j neo4j = Neo4j.getInstance();
private static final String[] COLORS = {"cyan", "green", "orange", "pink", "yellow", "purple", "grey","orange","purple", "green", "yellow"};
private static final String[] COURSE_COLORS = {"cyan", "green", "orange", "pink", "yellow", "purple", "grey","orange","purple", "green", "yellow","solid-green","solid-blue","magenta",
"light-pink","light-orange","solid-red","light-red","light-green","solid-orange"};
private EleveService eleveService = new DefaultEleveService();
protected static final Logger log = LoggerFactory.getLogger(DefaultUtilsService.class);
@Override
public <T, V> void addToMap(V value, T key, Map<T, List<V>> map) {
if (map.get(key) == null) {
map.put(key, new ArrayList<V>());
}
map.get(key).add(value);
}
@Override
public JsonObject[] convertTo (Object[] value) {
ArrayList<JsonObject> result = new ArrayList<>();
for(Object o : value) {
result.add(new JsonObject((Map<String, Object>) o));
}
return result.toArray(new JsonObject[0]);
}
public String getColor(String classes) {
byte[] bytes = classes.getBytes();
int number = 0;
for (int i = 0; i < bytes.length ; i++){
number += (int) bytes[i];
}
number = (int) Math.abs(Math.floor(Math.sin( (double) number) * 10 ) ) ;
return COLORS[number] ;
// return "solid-green";
}
@Override
public String getSubjectColor(String subjectId) {
byte[] bytes = subjectId.getBytes();
int number = 0;
for (int i = 0; i < bytes.length ; i++){
number += (int) bytes[i];
}
number = number % COURSE_COLORS.length ;
return COURSE_COLORS[number] ;
// return "solid-green";
}
@Override
public void getTypeGroupe(String[] id_classes, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
JsonObject values = new JsonObject();
query.append("MATCH (c:Class) WHERE c.id IN {id_classes} RETURN c.id AS id, c IS NOT NULL AS isClass UNION ")
.append(" MATCH (g:FunctionalGroup) WHERE g.id IN {id_classes} RETURN g.id AS id, NOT(g IS NOT NULL) ")
.append(" AS isClass UNION")
.append(" MATCH (g:ManualGroup) WHERE g.id IN {id_classes} RETURN g.id AS id, NOT(g IS NOT NULL) ")
.append(" AS isClass ");
values.put("id_classes", new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(id_classes)))
.put("id_classes", new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(id_classes)));
neo4j.execute(query.toString(), values, Neo4jResult.validResultHandler(handler));
}
@Override
public JsonObject mapListNumber(JsonArray list, String key, String value) {
JsonObject values = new JsonObject();
JsonObject o;
for (int i = 0; i < list.size(); i++) {
o = list.getJsonObject(i);
values.put(o.getString(key), o.getInteger(value));
}
return values;
}
@Override
public JsonObject mapListString (JsonArray list, String key, String value) {
JsonObject values = new JsonObject();
JsonObject o;
for (int i = 0; i < list.size(); i++) {
o = list.getJsonObject(i);
values.put(o.getString(key), o.getString(value));
}
return values;
}
@Override
public JsonArray saUnion(JsonArray recipient, JsonArray list) {
for (int i = 0; i < list.size(); i++) {
recipient.add(list.getValue(i));
}
return recipient;
}
public JsonArray saUnionUniq(JsonArray recipient, JsonArray list) {
for (int i = 0; i < list.size(); i++) {
JsonObject element = (JsonObject) list.getValue(i);
Object eleve = recipient.getList().stream()
.filter(p ->
((JsonObject) p).getString("idEleve").equals(element.getString("idEleve"))
/*&& ((JsonObject) p).getString("idClasse").equals(element.getString("idClasse"))*/
)
.findFirst()
.orElse(null);
if(eleve == null) {
recipient.add(element);
}
}
return recipient;
}
@Override
public JsonArray sortArray(JsonArray jsonArr, String[] sortedField) {
JsonArray sortedJsonArray = new JsonArray();
List<JsonObject> jsonValues = new ArrayList<JsonObject>();
if (jsonArr.size() > 0 && ! (jsonArr.getValue(0) instanceof JsonObject)) {
return jsonArr;
}
else{
for (int i = 0; i < jsonArr.size(); i++) {
jsonValues.add(jsonArr.getJsonObject(i));
}
Collections.sort(jsonValues, new Comparator<JsonObject>() {
@Override
public int compare(JsonObject a, JsonObject b) {
String valA = new String();
String valB = new String();
try {
for (int i = 0; i < sortedField.length; i++) {
valA += ((String) a.getValue(sortedField[i])).toLowerCase();
valB += ((String) b.getValue(sortedField[i])).toLowerCase();
}
} catch (Exception e) {
//do something
log.error("Pb While Sorting Two Array",e);
}
return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.size(); i++) {
sortedJsonArray.add(jsonValues.get(i));
}
return sortedJsonArray;
}
}
@Override
public void getTitulaires(String psIdRemplacant, String psIdEtablissement, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
JsonArray values = new fr.wseduc.webutils.collections.JsonArray();
query.append("SELECT DISTINCT id_titulaire ")
.append("FROM "+ Viescolaire.EVAL_SCHEMA +".rel_professeurs_remplacants ")
.append("WHERE id_remplacant = ? ")
.append("AND id_etablissement = ? ")
.append("AND date_debut <= current_date ")
.append("AND current_date <= date_fin ");
values.add(psIdRemplacant);
values.add(psIdEtablissement);
Sql.getInstance().prepared(query.toString(), values, validResultHandler(handler));
}
@Override
public Handler<Message<JsonObject>> addStoredDeletedStudent( JsonArray idClasse,
String idStructure,String[] idEleves, String [] sortedField,
Long idPeriode,
Handler<Either<String, JsonArray>> handler) {
return new Handler<Message<JsonObject>>() {
public void handle(Message<JsonObject> event) {
if ("ok".equals(((JsonObject)event.body()).getString("status"))) {
JsonArray rNeo = ((JsonObject)event.body()).getJsonArray("result",
new fr.wseduc.webutils.collections.JsonArray());
JsonArray idsNeo = new fr.wseduc.webutils.collections.JsonArray();
for (int i=0; i<rNeo.size(); i++) {
String idEleve = rNeo.getJsonObject(i).getString("id");
if (idEleve == null) {
idEleve = rNeo.getJsonObject(i).getString("idEleve");
}
idsNeo.add(idEleve);
}
eleveService.getStoredDeletedStudent(idClasse,idStructure, idEleves, rNeo,
new Handler<Either<String, JsonArray>>() {
public void handle(Either<String, JsonArray> event) {
if (event.isRight()) {
JsonArray rPostgres = event.right().getValue();
if(rPostgres !=null && rPostgres.size() > 0){
/*JsonArray elevesToDelete = (JsonArray) rPostgres.stream().filter( eleveDeleted ->{
return( idsNeo.contains(((JsonObject)eleveDeleted).getString("id")));
}).collect(Collectors.toList());
elevesToDelete.forEach(eleveDeleted -> {
rPostgres.remove(eleveDeleted);
} );*/
List<Object> eleveNeoInrPostgres = rPostgres.stream().filter(eleveDeleted ->
idsNeo.contains(((JsonObject)eleveDeleted).getString("id"))).collect(Collectors.toList());
eleveNeoInrPostgres.forEach(eleveDeleted -> {
rPostgres.remove(eleveDeleted);
} );
}
JsonArray result = saUnion(rNeo, rPostgres);
if (null == idPeriode) {
handler.handle(new Either.Right(sortArray(result, sortedField)));
}
else {
new DefaultPeriodeService().getPeriodes(null,
(String[])idClasse.getList().toArray(new String[1]),
new Handler<Either<String, JsonArray>>() {
@Override
public void handle(Either<String, JsonArray> message) {
if (message.isRight()) {
JsonArray periodes = message.right().getValue();
JsonArray elevesAvailable = new JsonArray();
JsonObject periode = null;
for (int i = 0; i < periodes.size(); i++) {
if (idPeriode.intValue()
== ((JsonObject) periodes.getJsonObject(i))
.getInteger("id_type").intValue()) {
periode = (JsonObject) periodes.getJsonObject(i);
break;
}
}
if (periode != null) {
String debutPeriode = periode.getString("timestamp_dt")
.split("T")[0];
String finPeriode = periode.getString("timestamp_fn")
.split("T")[0];
DateFormat formatter =
new SimpleDateFormat("yy-MM-dd");
try {
final Date dateDebutPeriode =
formatter.parse(debutPeriode);
final Date dateFinPeriode =
formatter.parse(finPeriode);
getAvailableStudent(result, idPeriode,
dateDebutPeriode, dateFinPeriode,
sortedField,handler);
} catch (ParseException e) {
String messageLog = "Error :can not calcul students " +
"of groupe : " + idClasse;
log.error(messageLog, e);
handler.handle(new Either.Left<>(messageLog));
}
} else {
handler.handle(new Either.Right<>(sortArray(result,
sortedField)));
}
}
}
});
}
} else {
handler.handle(new Either.Right<>(rNeo));
}
}
});
} else {
handler.handle(new Either.Left<>("Error While get User in Neo4J "));
}
}
};
}
public void getAvailableStudent (JsonArray students, Long idPeriode,
Date dateDebutPeriode, Date dateFinPeriode,String [] sortedField,
Handler<Either<String, JsonArray>> handler ) {
JsonArray eleveAvailable = new JsonArray();
for (int i = 0; i < students.size(); i++) {
JsonObject student = (JsonObject)students.getValue(i);
if ( idPeriode == null ||
student.getValue("deleteDate") == null ){
eleveAvailable.add(student);
}
// Sinon S'il sa date sa suppression survient avant la fin de
else {
Date deleteDate = new Date();
if (student.getValue("deleteDate")
instanceof Number) {
deleteDate = new Date(student.getLong("deleteDate"));
}
else {
try {
deleteDate = new SimpleDateFormat("yy-MM-dd")
.parse(student.getString("deleteDate").split("T")[0]);
} catch (ParseException e) {
String messageLog = "PB While read date of deleted Student : "
+ student.getString("id");
log.error(messageLog, e);
}
}
if ( (deleteDate.after(dateFinPeriode) || deleteDate.equals(dateFinPeriode))
||
((deleteDate.after(dateDebutPeriode)
|| deleteDate.equals(dateDebutPeriode))
&& (deleteDate.before(dateFinPeriode)
|| deleteDate.equals(dateFinPeriode)))) {
eleveAvailable.add(student);
}
}
}
handler.handle(new Either.Right<>(sortArray(eleveAvailable,sortedField)));
}
@Override
public Handler<Message<JsonObject>> getEleveWithClasseName(String[] idClasses, String[] idEleves, Long idPeriode,
Handler<Either<String, JsonArray>> handler) {
return new Handler<Message<JsonObject>>() {
public void handle(Message<JsonObject> eventNeo) {
if ("ok".equals(((JsonObject) eventNeo.body()).getString("status"))) {
JsonArray rNeo = eventNeo.body().getJsonArray("result");
new DefaultEleveService().getStoredDeletedStudent(
(null != idClasses)?new JsonArray(Arrays.asList(idClasses)) : null,
null, idEleves, rNeo,
new Handler<Either<String, JsonArray>>() {
public void handle(Either<String, JsonArray> eventPostgres) {
if (eventPostgres.isLeft()) {
handler.handle(new Either.Right<>(rNeo));
}
else {
DefaultUtilsService utilsService = new DefaultUtilsService();
JsonArray rPostgres = eventPostgres.right().getValue();
String[] idClassePostgresStudents = new String[rPostgres.size()];
for (int i=0; i< rPostgres.size(); i++) {
idClassePostgresStudents[i] = rPostgres.getJsonObject(i)
.getString("idClasse");
}
getClassesName(idClassePostgresStudents,
new Handler<Either<String, JsonArray>>() {
public void handle(Either<String, JsonArray> classeNamesEvent) {
if (classeNamesEvent.isLeft()) {
handler.handle(new Either.Left<>("PB While getting Classe Name"));
}
else {
JsonArray classesNames = classeNamesEvent.right().getValue();
HashMap<String,String> mapClasseName = new LinkedHashMap<>();
// On stocke les noms des classes dans une map
for (int i= 0; i < classesNames.size(); i++) {
if(mapClasseName.get(classesNames.getJsonObject(i)
.getString("idClasse")) == null){
mapClasseName.put(classesNames.getJsonObject(i)
.getString("idClasse"),
classesNames.getJsonObject(i)
.getString("name"));
}
}
JsonArray studentPostgres = new JsonArray();
for(int i=0; i< rPostgres.size(); i++) {
JsonObject o = new JsonObject();
JsonObject student = rPostgres.getJsonObject(i);
String studentIdClasse = rPostgres.getJsonObject(i)
.getString("idClasse");
o.put("name", mapClasseName.get(studentIdClasse));
o.put("classeName", mapClasseName.get(studentIdClasse));
o.put("idClasse", studentIdClasse);
o.put("idEleve", student.getString("idEleve"));
o.put("lastName", student.getString("lastName"));
o.put("firstName", student.getString("firstName"));
o.put("deleteDate", student.getString("deleteDate"));
o.put("displayName", student.getString("displayName"));
o.put("idGroupes", student.getString("idGroupes"));
o.put("idEtablissement",student.getString("idEtablissement"));
o.put("birthDate",student.getString("birthDate"));
studentPostgres.add(o);
}
DefaultUtilsService utilsService = new DefaultUtilsService();
JsonArray result = utilsService.saUnionUniq(rNeo, studentPostgres);
String [] sortedField = new String[2];
sortedField[0] = "lastName";
sortedField[1] = "firstName";
if (null == idPeriode) {
handler.handle(new Either.Right(
utilsService.sortArray(result, sortedField)));
}
else {
new DefaultPeriodeService().getPeriodes(null,
idClasses,
new Handler<Either<String, JsonArray>>() {
@Override
public void handle(Either<String, JsonArray>
message) {
if (message.isRight()) {
JsonArray periodes = message.right()
.getValue();
JsonArray elevesAvailable = new JsonArray();
JsonObject periode = null;
for (int i = 0; i < periodes.size(); i++) {
if (idPeriode.intValue()
== ((JsonObject) periodes.getJsonObject(i))
.getInteger("id_type").intValue()) {
periode = (JsonObject) periodes.getJsonObject(i);
break;
}
}
if (periode != null) {
String debutPeriode = periode.getString("timestamp_dt")
.split("T")[0];
String finPeriode = periode.getString("timestamp_fn")
.split("T")[0];
DateFormat formatter =
new SimpleDateFormat("yy-MM-dd");
try {
final Date dateDebutPeriode =
formatter.parse(debutPeriode);
final Date dateFinPeriode =
formatter.parse(finPeriode);
utilsService.getAvailableStudent(
result, idPeriode,
dateDebutPeriode,
dateFinPeriode,
sortedField,handler);
} catch (ParseException e) {
String messageLog = "Error :can not"
+
"calcul students " +
"of groupe : " + idClasses[0];
log.error(message,e);
handler.handle(new Either.Left<>(messageLog));
}
} else {
handler.handle(
new Either.Right<>(
utilsService.sortArray(result,
sortedField)));
}
}
}
});
}
}
}
});
}
}
});
} else {
handler.handle(new Either.Left<>("Pb While getting Student in Neo"));
}
}
};
}
private void getClassesName(String[] idClasses, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
JsonObject params = new JsonObject();
query.append("MATCH (c:Class)-[BELONGS]->(s:Structure) WHERE c.id IN {idClasses} ")
.append(" RETURN c.id as idClasse, c.name as name ORDER BY c.name ");
params.put("idClasses", new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(idClasses)));
neo4j.execute(query.toString(),params, Neo4jResult.validResultHandler(handler));
}
@Override
public void getIdGroupByExternalId(List<String> externalIdGroups, Handler<Either<String, JsonArray>> handler){
StringBuilder query = new StringBuilder();
query.append("MATCH (g:Group) " +
"WHERE g.externalId IN {id} " +
"RETURN g.id as id, g.externalId as externalId " +
"UNION MATCH (c:Class) " +
"WHERE c.externalId IN {id} " +
"RETURN c.id as id, c.externalId as externalId");
JsonObject values = new JsonObject();
values.put("id", new fr.wseduc.webutils.collections.JsonArray(externalIdGroups));
neo4j.execute(query.toString(), values, Neo4jResult.validResultHandler(handler));
}
@Override
public void getStructure(String idStructure, Handler<Either<String, JsonObject>> handler){
StringBuilder query = new StringBuilder();
query.append("MATCH (s:Structure {id: {idStructure}}) return s ");
JsonObject params = new JsonObject().put("idStructure", idStructure);
neo4j.execute(query.toString(), params, Neo4jResult.validUniqueResultHandler(handler));
}
@Override
public void getStructures(Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
query.append("MATCH (s:Structure) return s.id ");
neo4j.execute(query.toString(), new JsonObject(), Neo4jResult.validResultHandler(handler));
}
// @Override
// public void getIdStructuresByExternalId(List<String> externalIdStructures, Handler<Either<String, JsonArray>> handler){
// StringBuilder query = new StringBuilder();
// query.append("MATCH (s:Structure) WHERE s.externalId IN {id} RETURN s.id as structureIds");
// Neo4j.getInstance().execute(query.toString(), new JsonObject().put("id",new fr.wseduc.webutils.collections.JsonArray(externalIdStructures)), Neo4jResult.validResultHandler(handler));
public JsonObject findWhere(JsonArray collection, JsonObject oCriteria) {
Integer matchNeeded = oCriteria.size();
Integer matchFound = 0;
for (Object o : collection) {
JsonObject object = (JsonObject) o;
for (Map.Entry<String, Object> criteriaValue : oCriteria.getMap().entrySet()) {
if (object.containsKey(criteriaValue.getKey()) && object.getValue(criteriaValue.getKey()).equals(criteriaValue.getValue())) {
matchFound++;
if (matchFound.equals(matchNeeded)) {
return object;
}
}
}
matchFound = 0;
}
return null;
}
public Object find(Iterable collection, Predicate predicate) {
for (Object o : collection) {
if (predicate.test(o)) {
return o;
}
}
return null;
}
public JsonArray filter(JsonArray collection, Predicate predicate) {
JsonArray result = new JsonArray();
for(Object o : collection) {
if(predicate.test(o)) {
result.add(o);
}
}
return result;
}
public Collection pluck(Iterable collection, String key) {
Set result = new HashSet();
for (Object o : collection) {
JsonObject castedO = (JsonObject) o;
if (castedO.containsKey(key)) {
if(castedO.getValue(key) instanceof Collection) {
result.addAll((Collection) castedO.getValue(key));
} else {
result.add(castedO.getValue(key));
}
}
}
return result;
}
public Collection map(Iterable collection, Function fct) {
List result = new ArrayList();
for(Object o : collection) {
result.add(fct.apply(o));
}
return result;
}
}
|
package gate.plugin.learningframework.engines;
import cc.mallet.classify.Classifier;
import cc.mallet.topics.ParallelTopicModel;
import cc.mallet.topics.TopicInferencer;
import cc.mallet.topics.TopicModelDiagnostics;
import cc.mallet.types.Instance;
import gate.Annotation;
import gate.AnnotationSet;
import gate.plugin.learningframework.EvaluationMethod;
import gate.plugin.learningframework.ModelApplication;
import static gate.plugin.learningframework.engines.Engine.FILENAME_MODEL;
import gate.util.GateRuntimeException;
import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static gate.plugin.learningframework.LFUtils.newURL;
import gate.plugin.learningframework.data.CorpusRepresentationMalletLDA;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Johann Petrak
*/
public class EngineMBTopicsLDA extends EngineMBMallet {
// not used for now
// private static final Logger LOGGER = Logger.getLogger(EngineMBTopicsLDA.class);
protected TopicModelDiagnostics tmd;
protected ParallelTopicModel tm;
public ParallelTopicModel getTopicModel() {
return tm;
}
public TopicModelDiagnostics getTopicModelDiagnostics() {
return tmd;
}
public EngineMBTopicsLDA() { }
public List<Map<String,Double>> getTopicWordScores(ParallelTopicModel tm) {
List<Map<String,Double>> perTopicWord2Score = new ArrayList<>(tm.numTopics);
for(int i=0; i<tm.numTopics; i++) {
perTopicWord2Score.add(new HashMap<>());
}
// modified from Mallet ParallelTopicModel code
for(int topicnr=0; topicnr<tm.numTopics; topicnr++) {
for(int type=0; type<tm.numTypes; type++) {
int[] topicCounts=tm.typeTopicCounts[type];
double weight = tm.beta;
int index = 0;
while (index < topicCounts.length && topicCounts[index] > 0) {
// Mallet really stores both the count and the topic number in the
// topicCounts variable: the actual counts are in the highest bits
// while the topic number is in as many lowest bits as necessary.
// The topic mask is ones for those lowest bits.
int currentTopic = topicCounts[index] & tm.topicMask;
if(currentTopic == topicnr) {
weight += topicCounts[index] >> tm.topicBits; // get the actual count
break;
}
index++;
}
perTopicWord2Score.get(topicnr).put((String)tm.alphabet.lookupObject(type), weight);
}
}
for(int i=0; i<perTopicWord2Score.size(); i++) {
Map<String,Double> unsortedMap = perTopicWord2Score.get(i);
// calculate sum
double sum = unsortedMap.entrySet().stream().mapToDouble(x -> x.getValue()).sum();
// remap values to 0..1, NOTE: sum should always be > 0!
unsortedMap.entrySet().stream().forEach(x -> unsortedMap.put(x.getKey(), x.getValue()/sum));
// sort and store result in a linked hash map
Map<String,Double> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream().
sorted(Map.Entry.<String, Double>comparingByValue().reversed()).
forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
// store the sorted map instead of the original one int th result
perTopicWord2Score.set(i, sortedMap);
}
return perTopicWord2Score;
}
public void printTopTopicWords(ParallelTopicModel tm, PrintStream pw, int numTopWords) {
List<Map<String,Double>> perTopicWord2Score = getTopicWordScores(tm);
for(int topicnr=0; topicnr<tm.numTopics; topicnr++) {
Map<String,Double> sortedWordScores = perTopicWord2Score.get(topicnr);
pw.print(topicnr);
pw.print("(");
pw.print(String.format(java.util.Locale.US,"%.4f", tm.alpha[topicnr]));
pw.print(")");
pw.print(":");
Iterator<Map.Entry<String,Double>> it = sortedWordScores.entrySet().iterator();
for(int i=0; i<numTopWords; i++) {
if(it.hasNext()) {
Entry<String,Double> entry = it.next();
pw.print(" ");
pw.print(entry.getKey());
pw.print(":");
pw.print(String.format(java.util.Locale.US,"%.4f", entry.getValue()));
} else {
break;
}
}
pw.println();
}
}
@Override
public void trainModel(File dataDirectory, String instanceType, String parmString) {
// TODO: at this point we could maybe remove low-frequency words.
// This would be possible by adding a vocab/stats object to count each
// entry in the alphabet and then going through the instances, using
// the FeatureSequence.prune method
System.err.println("EngineMalletClass.trainModel: trainer="+trainer);
System.err.println("EngineMalletClass.trainModel: CR="+corpusRepresentation);
// default values for those which can be set
int nrTopics = 10;
double alpha = 1.0;
double beta = 0.01;
int showNrTopWords = 20;
int showNrDocs = 5;
int showNrTopics = 10;
int optimizeInterval = 50;
boolean doDiagnostics = false;
int numThreads = Runtime.getRuntime().availableProcessors();
if(numThreads<1) {
numThreads = 1;
}
int seed = 0;
int maxCondModesIts = 0;
int displayInterval = 200;
int numIterations = 1000;
int numBurnin = 200;
Parms parmdef = new Parms(parmString,
"t:topics:i",
"T:stopics:i",
"p:procs:i",
"w:words:i",
"d:docs:i",
"s:seed:i",
"a:alpha:d",
"M:mcmi:i",
"b:beta:d",
"o:opti:i",
"D:diags:b",
"i:iters:i",
"B:burn:i",
"S:show:i"
);
nrTopics = (int) parmdef.getValueOrElse("topics", nrTopics);
alpha = (double) parmdef.getValueOrElse("alpha", alpha);
beta = (double) parmdef.getValueOrElse("beta", beta);
showNrTopWords = (int) parmdef.getValueOrElse("words", showNrTopWords);
showNrDocs = (int) parmdef.getValueOrElse("docs", showNrDocs);
numThreads = (int) parmdef.getValueOrElse("procs", numThreads);
seed = (int) parmdef.getValueOrElse("seed", seed);
maxCondModesIts = (int)parmdef.getValueOrElse("mcmi", maxCondModesIts);
optimizeInterval = (int)parmdef.getValueOrElse("opti", optimizeInterval);
doDiagnostics = (boolean)parmdef.getValueOrElse("diags", doDiagnostics);
numIterations = (int)parmdef.getValueOrElse("iters", numIterations);
numBurnin = (int)parmdef.getValueOrElse("burn", numBurnin);
displayInterval = (int)parmdef.getValueOrElse("show", displayInterval);
System.out.println("INFO: running Mallet LDA with parameters: topics="+nrTopics+
",alpha="+alpha+",beta="+beta+",words="+showNrTopWords+",procs="+numThreads+
",docs="+showNrDocs+",seed="+seed+",maxCondModesIts="+maxCondModesIts+
",optimizeInterval="+optimizeInterval+",doDiagnostics"+doDiagnostics+
",iters="+numIterations+",burnin="+numBurnin
);
tm = new ParallelTopicModel(nrTopics, alpha, beta);
// NOTE: this cauases the model to get saved by the standard mallet serialization process
model= tm;
tm.setTopicDisplay(displayInterval, showNrTopWords);
tm.setNumThreads(numThreads);
tm.setNumIterations(numIterations);
tm.setOptimizeInterval(optimizeInterval);
tm.setNumIterations(numIterations);
tm.setBurninPeriod(numBurnin);
tm.setRandomSeed(seed);
// For showing top documents see implementation of
// tm.printTopicDocuments(printwriter, showNrDocs);
tm.addInstances(corpusRepresentation.getRepresentationMallet());
try {
System.out.println("INFO: estimating the model...");
tm.estimate();
System.out.println("INFO: topics estimation finished");
if(maxCondModesIts > 0) {
System.out.println("INFO: maximizing using iterated conditional modes ...");
tm.maximize(maxCondModesIts);
System.out.println("INFO: maximizing finished");
}
} catch (IOException ex) {
throw new GateRuntimeException("Exception during training of model", ex);
}
System.out.println();
System.out.println("Top topic words and their scores:");
printTopTopicWords(tm, System.out, showNrTopWords);
System.out.println();
File topWordsPerTopicFile = new File(dataDirectory, "topWordsPerTopic.txt");
try (FileOutputStream fos = new FileOutputStream(topWordsPerTopicFile);
PrintStream out = new PrintStream(fos) )
{
System.out.println("INFO: writing top words per topic to "+topWordsPerTopicFile);
printTopTopicWords(tm, out, showNrTopWords);
} catch (Exception ex) {
throw new GateRuntimeException("Exception during writing of words per topic file", ex);
}
/* replaced by our own method above
try {
// Save the topicKeysFile
System.out.println("INFO: writing top words per topics to file "+topWordsPerTopicFile);
tm.printTopWords(topWordsPerTopicFile, showNrTopWords, false);
} catch (IOException ex) {
throw new GateRuntimeException("Exception during writing of top words per topic", ex);
}
*/
File topDocsPerTopicFile = new File(dataDirectory, "topDocsPerTopic.txt");
try (PrintWriter out = new PrintWriter(topDocsPerTopicFile) )
{
System.out.println("INFO: writing top documents per topic file "+topDocsPerTopicFile);
tm.printTopicDocuments(out, showNrDocs);
} catch (Exception ex) {
throw new GateRuntimeException("Exception during writing of docs per topic file", ex);
}
File topTopicPerDocFile = new File(dataDirectory, "topTopicPerDoc.txt");
try (PrintWriter out = new PrintWriter(topTopicPerDocFile) )
{
System.out.println("INFO: writing top topics per document file "+topTopicPerDocFile);
tm.printDocumentTopics(out, 0.0, showNrTopics);
} catch (Exception ex) {
throw new GateRuntimeException("Exception during writing of topics per doc file", ex);
}
File topicWordWeightsFile = new File(dataDirectory, "topicWordWeights.txt");
System.out.println("INFO: writing topic word weights to "+topicWordWeightsFile);
try {
tm.printTopicWordWeights(topicWordWeightsFile);
} catch (IOException ex) {
throw new GateRuntimeException("Exception during writing of topic word weights file", ex);
}
tmd = null; // if we do not run it, null indicates that we do not need to save it!
if(doDiagnostics) {
System.out.println("INFO: calculating topic model diagnostics...");
tmd = new TopicModelDiagnostics(tm, corpusRepresentation.getRepresentationMallet().getAlphabet().size());
System.out.println("Topic Model Coherence: "+Arrays.toString(tmd.getCoherence().scores));
updateInfo();
}
}
@Override
protected void saveModel(File directory) {
System.out.println("INFO: saving model");
super.saveModel(directory);
// in addition to saving the model, we also write out some additional files
// generated from the diagnostics
if(tmd != null) {
try (
PrintWriter pw = new PrintWriter(new File(directory, "diagnostics.xml"), "UTF-8");
)
{
System.out.println("INFO: saving diagnostics.xml file");
pw.print(tmd.toXML());
} catch (FileNotFoundException | UnsupportedEncodingException ex) {
throw new GateRuntimeException("Exception when writing diagnostics.xml",ex);
}
}
}
@Override
protected void loadAndSetCorpusRepresentation(URL directory) {
if(corpusRepresentation==null) {
corpusRepresentation = CorpusRepresentationMalletLDA.load(directory);
}
}
@Override
protected void loadModel(URL directory, String parms) {
URL modelFile = newURL(directory, FILENAME_MODEL);
Classifier classifier;
try (InputStream is = modelFile.openStream();
ObjectInputStream ois = new ObjectInputStream(is)) {
ParallelTopicModel ptm = (ParallelTopicModel) ois.readObject();
model=ptm;
} catch (IOException | ClassNotFoundException ex) {
throw new GateRuntimeException("Could not load Mallet model", ex);
}
}
@Override
public List<ModelApplication> applyModel(
AnnotationSet instanceAS, AnnotationSet inputAS, AnnotationSet sequenceAS, String parms) {
// NOTE: this generic method cannot be used for LDA since we need to know
// the token feature. Instead we have an engine specific method (see below)
// Also, we directly store the results in the instance annotations, instead of
// returning a model application instance (which only works for classification/regression)
throw new GateRuntimeException("Method applyModel cannot be used with EngineMBTopicsLDA, use applyTopicModel");
}
public void applyTopicModel(AnnotationSet instanceAS, AnnotationSet inputAS,
String tokenFeature, String parms) {
CorpusRepresentationMalletLDA data = (CorpusRepresentationMalletLDA)corpusRepresentation;
data.stopGrowth();
int numIterations = 10;
int burnIn = 10;
int thinning = 0;
int seed = 0;
Parms parmdef = new Parms(parms,
"i:iters:i",
"B:burnin:i",
"T:thinning:i",
"s:seed:i"
);
numIterations = (int) parmdef.getValueOrElse("iters", numIterations);
burnIn = (int) parmdef.getValueOrElse("burnin", burnIn);
thinning = (int) parmdef.getValueOrElse("thinning", thinning);
seed = (int) parmdef.getValueOrElse("seed", seed);
ParallelTopicModel tm = (ParallelTopicModel)model;
TopicInferencer ti = tm.getInferencer();
tm.setRandomSeed(seed);
for(Annotation instAnn : instanceAS.inDocumentOrder()) {
// System.err.println("DEBUG: adding instance annotation "+instAnn);
Instance inst = data.getInstanceFor(gate.Utils.start(instAnn), gate.Utils.end(instAnn), inputAS, tokenFeature);
// System.err.println("DEBUG: Instance data is "+inst.getData());
// System.err.println("DEBUG: got inferencer "+ti);
// NOTE: see http://mallet.cs.umass.edu/api/cc/mallet/topics/TopicInferencer.html#getSampledDistribution(cc.mallet.types.Instance,%20int,%20int,%20int)
double[] tdist = ti.getSampledDistribution(inst, numIterations, thinning, burnIn);
List<Double> tdistlist = new ArrayList<>(tdist.length);
int i = 0;
int bestTopic = -1;
double bestProb = -999.99;
for(double val : tdist) {
tdistlist.add(val);
if(val > bestProb) {
bestTopic = i;
bestProb = val;
}
i++;
}
instAnn.getFeatures().put("LF_MBTopicsLDA_TopicDist", tdistlist);
// Also add a feature that gives the index and word list of the most likely topic
instAnn.getFeatures().put("LF_MBTopicsLDA_MLTopic", bestTopic);
instAnn.getFeatures().put("LF_MBTopicsLDA_MLTopicProb", bestProb);
// TODO: to add the topic words we have to pre-calculate the top k words for each topic
// and assign the list for topic k here!
// instAnn.getFeatures().put("LF_MBTopicsLDA_MLTopicWords", bestProb);
}
}
@Override
public void initializeAlgorithm(Algorithm algorithm, String parms) {
// NOTE: for LDA we do not do anything in here, everything happens in the train() method
}
@Override
public EvaluationResult evaluate(String algorithmParameters, EvaluationMethod evaluationMethod, int numberOfFolds, double trainingFraction, int numberOfRepeats) {
throw new GateRuntimeException("Method evaluate not available for EngineMBTopicsLDA");
}
@Override
protected void initWhenLoading(URL dir, String parms) {
super.initWhenLoading(dir, parms);
corpusRepresentation.stopGrowth();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.